How can I create custom error page for 500 Internal server error in next.js app router?

3k views Asked by At

In the previous versions of next.js and current version with page router, I know that there is an ability to handle it buy only creating a 500.js/jsx/tsx file and export default a react component. but I didn't find anything about it in app router.

2

There are 2 answers

1
Amrita Pathak On

As of NextJS v14, with App router,

This is not possible. (Some pertinent discussions can be found on github)

As a workaround,

You could add a specific route, /error (/app/error/page.tsx) and then redirect to this path when a server error happens.

For example, on your server component (api/route.js)

import { redirect } from "next/navigation";

try {
   // something that throws an error
   throw new Error("Internal server error");
}
catch (e) {
   // your should probably log the error as well 
   redirect('/error?status=500&message=servererror');
}

Then in your /app/error/page.tsx

const ErrorPage = ({ searchParams }: { searchParams: { [key: string]: string | string[] | undefined } }) => {
  return (
    <main>
      <h1>Error {searchParams.status}</h1>
      <p>{searchParams.message}</p>
    </main>
  );
};

export default ErrorPage;

To redirect all 5xx errors to your error page, you could write a wrapper like

/* /app/helpers/errorHandler.js */

import { redirect } from "next/navigation";

function withErrorHandler(fn) {
  return async function (request, ...args) {
    try {
      return await fn(request, ...args);
    } catch (error) {
      // Log the error to a logging system
      
      // Respond with a generic 500 Internal Server Error
      redirect('/error?status=500&message=servererror');
    }
  };
}

export default withErrorHandler;


/**** Then use this in your routes (route.js) ****/

import "...";

export const GET = withErrorHandler(async (request) => {
  await runFunctionHelloWorld();
  // Return a successful response if no errors occurred
  return NextResponse.json({ success: true }, { status: 200 });
});

Reference for wrapper

0
Abdulbasit On

so basically you have to create an error.tsx file

for example

dashboard -page.tsx -error.tsx

page.tsx error.tsx