Home
Next.js
Error Handling in Next.js
Daniel Nguyen
Daniel Nguyen
September 25, 2026
1 min

Error handling in Next.js becomes much easier when you separate expected errors from unexpected errors.

Recover, Not Found, or Try Again — pick the right error path
Recover, Not Found, or Try Again — pick the right error path

Expected errors

These are problems that can happen normally, like failed requests or form validation. Instead of throw, return an error and handle it in the UI.

if (!res.ok) {
return { message: 'Failed to create post' }
}

notFound()

When the resource doesn’t exist, use notFound():

if (!post) {
notFound()
}

Then add not-found.tsx to render your 404 page.

Uncaught exceptions

This is where something actually breaks — usually a bug or an unexpected failure. Throw the error and let an Error Boundary handle it.

throw new Error('Something went wrong')

Create an error.tsx inside the route segment:

'use client'
export default function ErrorPage({
error,
retry,
}: {
error: Error
retry: () => void
}) {
return (
<>
<h2>Something went wrong!</h2>
<button onClick={retry}>Try again</button>
</>
)
}

Errors are caught by the nearest error boundary, so you can have different error.tsx files for different parts of your app.

One important detail

Error boundaries don’t catch errors inside normal event handlers like onClick. Handle those yourself with try/catch and component state. Errors thrown inside startTransition, however, can bubble to the nearest error boundary.

For smaller parts of the UI, Next.js also provides catchError() to create a custom error boundary. And for errors in the root layout, there’s global-error.tsx, which must render its own <html> and <body>.

The mental model

Expected error → return the error
Missing resource → notFound()
Unexpected crash → throw → error.tsx
Root layout → global-error.tsx

Tags

#NextJS

Share

Daniel Nguyen

Daniel Nguyen

Frontend Developer

Frontend developer specializing in React, Next.js, and JavaScript. Writing practical guides on modern web development at Dev98.

Expertise

React
Next.js
JavaScript
TypeScript
Python

Social Media

githublinkedinyoutubewebsite

Related Posts

Next.js
GSAP in Next.js: A Practical Guide
September 29, 2026
1 min
Dev98

Dev98

React · Next.js · Web development