Skip to content
Advertisement

how to cleanly handle errors in nextjs getStaticProps

I’m very busy at the moment with building my first Next.JS application (Next and Strapi). Now everything is working but i’m curious about what the best way is to implement error handling when using getStaticProps.

I tried a few things myself (passing multiple props etc, but that all didn’t work (typical unserialized JSON error). The thing I want to achieve is an error message on the page itself (e.g. /about) that no data was found. With an error message attached (statusCode).

I hope it’s possible, I did a lot research and found: https://github.com/vercel/next.js/pull/17755 this. But it’s not exactly what I’m looking for.

Advertisement

Answer

You can create custom 404 and 500 error pages. There is an option to show the statusCode however, you can tell Next to use the 404 page by returning notfound: true in getStaticProps.

If you return notfound: true, the statusCode will always show the 404 page, and you know the status code will be 404.

Here is a example of catching errors in getStaticProps– this will generate your page or show your custom error page that is designed to your specifications.

export const getStaticProps = async () => {
  try {
    const { data, errors } = await someQuery();
    if (errors || !data) {
      return { notFound: true };
    }
    return { props: { data } };
  } catch () {
    return { notFound: true };
  }
};

A not so obvious additional use case of notFound is to use it to exclude a directory or page from production. The below check will skip the whole page or directory during next/export (SSG). This check be used to produce development only static pages.

If a single page in a directory has the check below, that page is skipped during the build process. If every page in a directory has the check – the whole directory will be skipped, including the folder.

export const getStaticProps = async () => {
  if (process.env.NODE_ENV === 'production') {
    return { notFound: true };
  }
  ...
};

Make sure you don’t include the routes you don’t want built in getStaticPaths too.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement