Error handling with error.tsx helps you show friendly messages when something goes wrong in your Next.js app. It keeps your app from crashing and helps users understand the problem.
Error handling with error.tsx in NextJS
'use client'; export default function Error({ error, reset }) { return ( <main> <h1>Something went wrong!</h1> <p>{error.message}</p> <button onClick={() => reset()}>Try again</button> </main> ); }
The Error component receives two props: error (the error object) and reset (a function to retry rendering).
Place error.tsx inside the folder of the route you want to handle errors for.
'use client'; export default function Error({ error, reset }) { return ( <div> <h2>Error occurred:</h2> <pre>{error.message}</pre> <button onClick={() => reset()}>Reload</button> </div> ); }
role="alert" and aria-label on the button.'use client'; export default function Error({ error, reset }) { return ( <section role="alert"> <h1>Oops!</h1> <p>We hit a problem: {error.message}</p> <button onClick={() => reset()} aria-label="Try again">Try again</button> </section> ); }
This example shows a page that throws an error when you click the button. The error.tsx file catches the error and shows a friendly message with a button to try again.
import { useState } from 'react'; 'use client'; export default function Page() { const [throwError, setThrowError] = useState(false); if (throwError) { throw new Error('This is a test error'); } return ( <main> <h1>Welcome to the page</h1> <button onClick={() => setThrowError(true)}>Cause Error</button> </main> ); } // error.tsx 'use client'; export default function Error({ error, reset }) { return ( <main role="alert"> <h1>Oops! Something went wrong.</h1> <p>{error.message}</p> <button onClick={() => reset()} aria-label="Try again">Try again</button> </main> ); }
Always provide a way to reset or retry after an error to improve user experience.
Use semantic HTML and ARIA roles for accessibility in your error UI.
Place error.tsx in the route folder where you want to handle errors specifically.
Error handling with error.tsx helps catch and show errors in Next.js routes.
It improves user experience by showing friendly messages and retry options.
Use accessible HTML and place the file in the right route folder.