Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js dynamic page params for static export

I have page which depends on route params (ex.: slug) like so http://example.com/blog/:slug. This route path is defined properly in my next.config.js file:

module.exports = withPlugins(plugins, {
  exportPathMap: (defaultPathMap) => {
    return {
      '/': { page: '/home/home' },
      '/blog/:slug': { page: '/careers/careers' }
    }
  }
});

This works fine when running the project in dev mode but once i export the project as static the route is not accessible and i get the regular 404 error from next.

Is there a way to fix this without using query parameters? http://example.com/?slug=123

This solution https://github.com/zeit/next.js/blob/canary/examples/with-static-export/next.config.js is also not acceptable since the posts come from backend CMS

like image 449
prototype Avatar asked Oct 16 '22 05:10

prototype


2 Answers

This is not possible because Next.js static export generates, well, static html pages. If you think about it, for this to work Next.js would somehow have to export every possible combination of letters valid in a url segment, which is not a good idea at all.

The closest you could get is using query parameters and the as attribute, for example when linking to a page:

<Link href='/blog/page?slug=SLUG_HERE' as='/blog/slug'>
  // Link content here
</Link>

This only breaks when the user tries to link to or reload the page because there is no server-side support for the masking. You could theoretically use Nginx or Apache to proxy (is proxy the right word?) requests from /blog/SLUG_HERE to /blog/page?slug=SLUG_HERE. This is left up to you to figure out.

like image 169
Kognise Avatar answered Nov 06 '22 00:11

Kognise


To handle dynamic paths in your next js project (provided you are going through the export route!).

  • Ensure trailingSlash is set to false or not defined at all in your next.config.js file

This way, every request will land in the index component, and from here, you can just handle your path redirect.

if (window.location.pathname !== "/") {
   Router.push(window.location.pathname + window.location.search);
}

Ensure your project is mounted before doing this (e.g do this with useEffect hook)

like image 45
AdefemiGreat Avatar answered Nov 05 '22 23:11

AdefemiGreat