Next.js SSR for dynamic routes is failing

Hi:

I’m having an SSR problem with my site here: https://butwillitscale.com/posts/lets-party

The Let’s Party page is giving a 404 only when I server-render the route. When I visit it via a client-side transition, it works fine.

Original source repo: https://github.com/jplew/netlify-blog/blob/master/pages/posts/[slug].tsx

This is a problem only in production on Netlify. I don’t see this in my dev environment.

Furthermore, this seems to be unique to Netlify, because the exact same commit works fine on Now.sh: https://netlify-blog.now.sh/posts/lets-party

I’m thinking the culprit is in here:

PostPage.getInitialProps = async ctx => {
  const {
    query: { slug }
  } = ctx

  if (slug) {
    const post = await import(`../../content/posts/${slug}.md`)
    return { post }
  }
  return {}
}

I’m hoping someone could shed light on why this would fail on Netlify but work on another serverless host, Now.

Never mind, I figured it out.

I was doing a static HTML export, but I failed to read this part of the docs: Getting Started | Next.js

For dynamic routes to work properly with next export, you need to specify a exportPathMap in your next.config.js, like this:

module.exports = {
  exportPathMap: async function(
    defaultPathMap,
    { dev, dir, outDir, distDir, buildId }
  ) {
    return {
      "/": { page: "/" },
      "/posts/lets-party": {
        page: "/posts/[slug]",
        query: { slug: "lets-party" }
      },
      "/posts/some-food-for-thought": {
        page: "/posts/[slug]",
        query: { slug: "some-food-for-thought" }
      }
    }
  }
}
1 Like

Welcome to our Netlify community site. @jplew.

Thank you for following up and sharing your solution here. Hopefully, if someone runs in to a similar issue, their search will find this post and it will help others in the same situation.