throw an error with a statusCode inside NextJs to test the customized error page

You can create an exception in your component, e.g. null pointer. Though throwing an err should do as well.

Then you need to

yarn build && yarn start

When running the build you will see next.js showing your custom err page.


I ran into this issue as well, and I think the easiest way is to import the _error.js page into another test page and render it with the status code of your choice. You can find this in the Next.js docs here. The code example you'll find looks like this:

import Error from 'next/error'

export async function getServerSideProps() {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const errorCode = res.ok ? false : res.statusCode
  const json = await res.json()

  return {
    props: { errorCode, stars: json.stargazers_count },
  }
}

// Note the page returns your custom error page
export default function Page({ errorCode, stars }) {
  if (errorCode) {
    return <Error statusCode={errorCode} />
  }

  return <div>Next stars: {stars}</div>
}

You can import your custom error page into another page and make modifications there without having to run yarn build and yarn start. This is particularly useful if you want to update the styles or fix any issues which might come up during development (e.g. localization).