A React Error Boundary Per Segment
error.tsx — Error Boundary
Drop an `error.tsx` in a segment and Next.js wraps it in a React error boundary. The file must be a Client Component and receives the error plus a `reset` function.
What you'll learn
- Create `error.tsx` with the `'use client'` directive
- Display the error message safely
- Call `reset()` to retry the segment
When a Server Component throws, Next.js looks for the nearest error.tsx and renders it
instead of the failing tree. It is a normal React error boundary, scoped to the segment.
Mark It With “use client”
Error boundaries must be Client Components because they catch errors and respond to user interaction (the retry button).
// app/dashboard/error.tsx
'use client'
import { useEffect } from 'react'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
console.error(error)
}, [error])
return (
<section>
<h2>Something went wrong.</h2>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</section>
)
} The digest field is a hashed identifier you can correlate with server logs without
leaking stack traces to users.
What reset Does
reset re-renders the segment. If the error was transient (a network blip), this clears
the boundary. If it was a deterministic bug, it will throw again and the boundary stays.
global-error.tsx For Catastrophes
At the very root of app/, you can add global-error.tsx. It catches errors thrown by
the root layout itself. Because it replaces the layout, it must render its own <html>
and <body> tags.
'use client'
export default function GlobalError({ reset }: { reset: () => void }) {
return (
<html><body>
<h1>Application error</h1>
<button onClick={reset}>Reload</button>
</body></html>
)
}