Global errors
This page explains how to handle errors at the root level of your Next.js application using the global error boundary.
Understanding global errors
While regular error boundaries handle errors within route segments, errors in the root layout require special handling since there’s no parent segment to catch them. Next.js provides a global-error.tsx
file specifically for these high-level application errors.
Creating a global error boundary
To implement global error handling, create a global-error.tsx
file in your app directory:
Directoryapp/
- global-error.tsx Global error boundary
- layout.tsx Root layout
- page.tsx
/
"use client";
export default function GlobalError({ error, reset,}: { error: Error; reset: () => void;}) { return ( <html lang="en"> <body> <div className="flex min-h-screen items-center justify-center"> <div className="text-center"> <h2 className="text-2xl font-bold mb-4">Something went wrong!</h2> <button onClick={() => reset()} className="bg-blue-500 text-white px-4 py-2 rounded" > Try again </button> </div> </div> </body> </html> );}
Testing global errors
To test the global error boundary, you can create a component that simulates errors in the root layout:
"use client";
export default function ErrorSimulator() { const triggerError = () => { throw new Error("Root layout error"); };
return ( <button onClick={triggerError} className="bg-red-500 text-white px-4 py-2 rounded" > Trigger Global Error </button> );}
Add this component to your root layout:
import ErrorSimulator from "./error-simulator";
export default function RootLayout({ children,}: { children: React.ReactNode;}) { return ( <html lang="en"> <body> <ErrorSimulator /> {children} </body> </html> );}
Important considerations
The global error boundary has two key differences from regular error boundaries:
- It must include
<html>
and<body>
tags since it completely replaces the root layout - It only functions in production mode. Development mode displays the default Next.js error overlay
To test the global error boundary:
- Build your application:
npm run build
- Start production server:
npm run start
- Click the error simulator button