How do you create a custom error page for a specific route segment in the App Router?
Short answer
You add a file named error.js inside a route folder, which must be a client component, and Next.js automatically shows it whenever an error occurs while rendering that route or any of its nested pages, letting you display a friendly message instead of a broken page.
Advertisement
AModel answer
You add a file named error.js inside a route folder, which must be a client component, and Next.js automatically shows it whenever an error occurs while rendering that route or any of its nested pages, letting you display a friendly message instead of a broken page.
'use client';
export default function Error({ error, reset }) {
return (
<div>
<h2>Something went wrong.</h2>
<button onClick={() => reset()}>Try again</button>
</div>
);
}Real-world example
A dashboard shows a friendly error message with a retry button whenever loading a user's data fails, instead of leaving them with a blank or broken screen.
Likely follow-ups
- Why does the error boundary file need to be a client component?
- What does the reset function actually do when called?
Related topics