grabury
grabury

Reputation: 5559

How to throw a 500 error from getStaticProps

I have a Nextjs app. I fetch data from a headless CMS to populate the 404 error page. If I don't get a reasonable response from the CMS I'd like to throw a 500 error.

Is this possible from getStaticProps?

Upvotes: 3

Views: 7964

Answers (1)

a.barbieri
a.barbieri

Reputation: 2596

Just throw the error, NextJS will take care of generating the 500 for you.

❌ Don't add a try {} catch(){} in getStaticProps.

✅ Do this:

export async function getServerSideProps() {
  throw new TypeError("Ops, CMS didn't return a reasonable response.");
}

BE AWARE: The error component is only used in production.


In development you’ll get an error with the call stack to know where the error originated from.

If you want to see what happens before deploying to production you can run the following command on your local env:

yarn build && NODE_ENV=production yarn start

⚠️ Re-run this command every-time you update the code otherwise you won't see any change.

See https://nextjs.org/docs/advanced-features/custom-error-page#more-advanced-error-page-customizing

Upvotes: 12

Related Questions