Next.js: Handle unexpected errors
13 June 2025 (Updated 13 June 2025)
For unexpected errors, you can throw them so that Next.js catches them via error boundaries.
Create an error boundary by adding a error.tsx
file inside a route folder and exporting a React component:
'use client' // Error boundaries must be Client Components
import { useEffect } from 'react'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
// Log the error to an error reporting service
console.error(error)
}, [error])
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
}
>
Try again
</button>
</div>
)
}
Errors will bubble up to the nearest parent error boundary.
Tagged:
Next.js recipes