Skip to content

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 its possible, i did a lot research and found: this. But its not exactly what I’m looking for.

Thankyou. Justian Spijkerbosch


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 };