How does global-error.tsx work in Next.js?
What global-error.tsx is
In Next.js, the app/global-error.tsx file:
- catches rendering, data fetching, and server component errors
- works at the level of the whole application
- overrides any layout
- is used when everything is broken
Error hierarchy (very important)
Next.js looks for an error boundary bottom to top:
segment/error.tsx ← priority #1
segment/layout.tsx
...
app/global-error.tsx ← last fallbackIf no matching error.tsx exists, global-error.tsx is used.
Where it lives
txt
app/
├─ layout.tsx
├─ global-error.tsx ← only here
└─ page.tsxOnly at the root of app/
global-error.tsx does not work inside segments.
Minimal example
tsx
"use client";
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return (
<html>
<body>
<h1>Something went seriously wrong</h1>
<p>{error.message}</p>
<button onClick={() => reset()}>
Try again
</button>
</body>
</html>
);
}Required points
use client- required- must return
<html>and<body> - receives:
error- the error objectreset()- re-renders the segment
What reset() does
- re-renders the application
- repeats
fetch, server components - useful for temporary errors (network, API)
Which errors it catches
- Catches: errors in Server Components
- Catches: errors in Client Components
- Catches: errors in
fetch() - Catches: errors in layout/page/template
- Does not catch: errors in event handlers (onClick)
- Does not catch: errors outside the React lifecycle
(for clicks - try/catch)
error.tsx vs global-error.tsx
error.tsx | global-error.tsx | |
|---|---|---|
| Scope | segment | entire application |
| Frequency | often | very rarely |
| UI | local | emergency |
| Overrides layout | No | Yes |
When global-error.tsx is NEEDED
- the database went down
- auth middleware broke
- an error in the root layout
- an unexpected runtime crash
- production fallback
When it is NOT needed
- errors specific to a page
- form validation
- business errors (404, forbidden)
- UI errors ->
error.tsx
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.