Search code examples
javascriptnext.jsnext-link

Next js with dynamic routing ([[…slug.js]]) to handle all URLs show 404 for links to home page - but only when deployed


I want a single dynamic route to handle all requests in this application, so I have written a file named [[...slug]].js to do so. I use getServerSideProps() for data loading, so it is server-side rendered, generally. I don't have any index.js files.

When it runs locally in development mode it works perfectly fine. When deployed (to Vercel) everything keeps working except links to /. <Link href={"/"}>… will request an index.json file from the server, get a 404 response and show error page. Why?


Solution

  • Gotcha!

    I use getServerSideProps() to fetch data depending on the slug. (Actual content is from Sanity.io and is queried to see if the content's slug property matches either slug from the URL or a default page slug).

    When running the app in local development mode with next dev, the params.slug argument will be undefined when loading the root ("/") URL. It has the same value whether the root URL is loaded by a refresh or a navigation action (clicking a link to /, using back button).

    However, when the site is deployed, this behaviour changes. params.slug is still undefined when the page is first loaded, but if it loads in response to a client-side navigation event the slug is suddenly set to index. Since I neither had a page with slug index nor ensured we used the default slug when index was requested, I got unexpected 404 responses. Using "index" as one of the values that triggers the default slug fixes it.

    I don't know if it is a bug in Next JS, but it was definitely a gotcha that confused me for a while.