error.js: Graceful Error Boundaries in Next.js
The `error.js` file acts as a UI safety net, catching runtime errors in a Next.js route segment to prevent a full app crash. Use it to display a custom error message and a "try again" button.
WHY IT EXISTS: In complex applications, errors are inevitable. A single component failing to render shouldn't crash the entire application. The error.js convention provides a built-in mechanism to isolate failures to specific parts of the UI, preserving the rest of the application's state and navigation.
THE MENTAL MODEL: Think of error.js as an automatic try-catch block for a specific part of your route tree. When an error occurs inside its boundary, instead of a broken page, Next.js renders your predefined error component, giving you control over the user's experience during failure.
HOW IT WORKS: You create a file named error.js inside a route directory (e.g., app/dashboard/error.js). This file must export a React component that is automatically treated as a Client Component. It receives two props: error, an object containing details about the error, and reset, a function that, when called, attempts to re-render the content within the boundary. This allows you to implement a "Try Again" button.
WHEN TO USE IT: Use error.js to handle runtime errors that might occur in Server or Client Components within a specific route segment. It's ideal for showing user-friendly messages for things like failed data fetches, rendering exceptions, or other unexpected issues, improving application resilience.
WHEN NOT TO USE IT: An error.js boundary does not catch errors originating from a layout.js or template.js file in the same segment; those errors will bubble up to the nearest error boundary in a parent route. It also won't catch errors from asynchronous callbacks outside the render lifecycle, like a setTimeout.
ONE CANONICAL EXAMPLE: A user visits /products/123. The page component tries to fetch product data, but the API is down. Instead of a generic browser error, the app/products/[id]/error.js component renders. It shows a message "Sorry, we couldn't load this product" and a button that calls the reset prop to try fetching the data again. The site's main navigation and header, defined in a parent layout, remain fully functional.
Read the original → nextjs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.