15th Apr 2022

Generating pages with getStaticPaths(Next.js)

Next.js has a function called getStaticPaths which when exported in a dynamic route will pre-render all the specified routes at build time paired with getStaticProps. I use these two functions to generate this page which you are currently reading from.

However, at one point I found myself disappointed by the fact that whenever I would add new logs on my /til route it would result in an error 404 and this would result in me having to rebuild the whole site which isn't optimal.

I later came to discover that this was caused by the fallback value in my getStaticPaths function being set to false which means that if you try to access a path that was not pre-rendered, it will give you an error 404 page.

export async function getStaticPaths() {
  const paths = await getTilDates();

  return {
    paths: paths.map((slug) => ({ params: { slug } })),
      fallback: false,
    };
}

After doing some research I found a solution in the Next.js docs which was to replace the false value with blocking.

If fallback is 'blocking', new paths not returned by getStaticPaths will wait for the HTML to be generated, identical to SSR (hence why blocking), and then be cached for future requests so it only happens once per path.

You can read more about in the Next.js docs