Error Handling

Next.js 13 introduced a new file convention, error.js, to help you handle errors in your application. This convention, built on React Error Boundaries, allows you to show a fallback if an error is thrown within the route subtree.

Error Boundaries

error.js defines the error boundary for a route segment and the children below it. It can be used to show specific error information, and functionality to attempt to recover from the error.

Create a default error boundary by adding a error.js as a file inside a folder:

Error File
app/feed/error.tsx
'use client';

import { useEffect } from 'react';

export default function Error({
  error,
  reset,
}: {
  error: Error;
  reset: () => void;
}) {
  useEffect(() => {
    // Log the error to an error reporting service
    console.error(error);
  }, [error]);

  return (
    <div>
      <p>Something went wrong!</p>
      <button onClick={() => reset()}>Reset error boundary</button>
    </div>
  );
}

Error boundaries must be Client Components.

In the same folder, error.js will be nested inside layout.js and template.js (if they exist). It'll wrap the page.js file and any children below in an error boundary, but not the layout or template at the same level.

How error.js works

During an error, layouts and templates above the boundary will remain interactive and their state will be preserved. To catch any errors in the layout or template, move the error boundary up to the parent segment.

Handling Server Errors

If an error is thrown during data fetching or inside a Server Component, Next.js will forward the resulting Error object to the nearest error.js file as the error prop.

When running next dev, the error will be serialized and forwarded from the Server Component to the client error.js. To ensure security when running next start in production, a generic error message is forwarded to error along with a .digest which contains a hash of the error message. This hash can be used to correspond to server logs.

Next Steps