How does the global-error.js file differ from a regular error.js file in the App Router?
Short answer
The global-error.js file, placed at the root of the app folder, catches errors that occur in the root layout itself, which regular error.js files cannot catch since they are nested inside the layout.
Advertisement
AModel answer
The global-error.js file, placed at the root of the app folder, catches errors that occur in the root layout itself, which regular error.js files cannot catch since they are nested inside the layout. It must include its own html and body tags since it replaces the entire root layout when an error happens there.
// app/global-error.js
'use client';
export default function GlobalError({ error, reset }) {
return (
<html>
<body>
<h2>A critical error occurred.</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
);
}Real-world example
An application catches a rare error that occurs inside its root layout itself using global-error.js, preventing the entire site from showing a completely blank white screen to visitors.
Likely follow-ups
- Why does global-error.js need its own html and body tags?
- How often does an error actually occur at the root layout level?
Related topics