reactjsnext.jshttp-status-code-500

How to simulate an HTTP 500 error on my React.js and Next.js apps?


I want to simulate this error so I can check a custom error page is displayed, not the HTTP 500 one, in light of the recent security vulnerability.

We include special processing in the site itself for 404 and 403 so I want to make sure that errors without special processing work too.


Solution

  • Normally a 500 response is returned when the server throws an error that is not explicitly handled. (see: Handling Server Errors). I've added two both app and pages scenarios down below. In both cases visiting /error should yield a 500 response.


    If you are using the app API, adding a page that throws an error on the server should do the trick.

    // app/error/page.jsx
    
    export default function Page() {
      throw new Error("don't catch me for a 500 response");
      return <h1>you should not see me</h1>;
    }
    

    Make sure the component is not marked as client component (no "use client" at the top of the file). When marked as client component the error would be thrown by the client, not by the server. Thus not producing a 500 response.


    If you're using the pages API a similar thing can be done. To run code on the server we use getServerSideProps (see: Server-side Rendering (SSR))

    // pages/error/index.jsx
    
    // this should run on the server
    export async function getServerSideProps() {
      throw new Error("don't catch me for a 500 response");
      return { props: {} };
    }
    
    export default function Index() {
      return <h1>you should not see me</h1>;
    }