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

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

Handle expected errors as application state. Use error boundaries to recover from unexpected rendering failures.

Different Types of Errors

Expected errors

Expected errors are normal outcomes of application logic. They should be handled explicitly and communicated clearly to users. Examples include:

  • A user submits an invalid phone number.
  • A product is out of stock.
  • A requested plant does not exist.

Unexpected errors

Unexpected errors occur when the application cannot complete an operation as intended. Examples include:

  • A database connection fails.
  • A Server Component throws an unhandled exception.
  • An unexpected response causes rendering to fail.

These errors require logging, a safe fallback UI, and sometimes a retry mechanism.

Server Actions with useActionState

Use React’s useActionState to read the result returned by the Server Action.

// app/checkout/form.tsx
'use client'
import { useActionState } from 'react'
import { createOrder } from '@/app/actions'
const initialState = {}
export function CheckoutForm() {
const [state, formAction, pending] =
useActionState(createOrder, initialState)
return (
<form action={formAction}>
<label htmlFor="phone">Phone number</label>
<input
id="phone"
name="phone"
type="tel"
required
/>
{state.fieldErrors?.phone && (
<p role="alert">
{state.fieldErrors.phone}
</p>
)}
{state.message && (
<p role="alert">{state.message}</p>
)}
<button type="submit" disabled={pending}>
{pending ? 'Placing order...' : 'Place order'}
</button>
</form>
)
}

An invalid phone number is an expected validation outcome. Returning an error keeps the user on the checkout form and allows them to correct their input without losing their current context.

Failed Data Fetches in Server Components

If the page cannot function without the requested data, you can throw an exception and let the nearest error boundary handle it.

// app/dashboard/page.tsx
export default async function DashboardPage() {
const response = await fetch(
`${process.env.API_URL}/dashboard`
)
if (!response.ok) {
throw new Error('Failed to load dashboard data')
}
const dashboard = await response.json()
return <Dashboard data={dashboard} />
}

The error will propagate to the nearest applicable error.tsx boundary.

Missing Resources with notFound()

A missing resource is usually a normal application outcome, not an unexpected crash. For example, a customer may visit a URL for a plant that has been removed from the catalog.

Next.js provides notFound() to render the nearest not-found.tsx UI.

// app/plants/[slug]/not-found.tsx
import Link from 'next/link'
export default function NotFound() {
return (
<div>
<h2>Plant not found</h2>
<p>
This plant may have been removed
or the link may be incorrect.
</p>
<Link href="/plants">
Browse all plants
</Link>
</div>
)
}

Use error.tsx as a Route-Level Error Boundary

The error.tsx file provides a fallback UI when an uncaught error occurs within its route segment.

It must be a Client Component because error boundaries need client-side React behavior.

// app/dashboard/error.tsx
'use client'
import { useEffect } from 'react'
export default function ErrorPage({
error,
retry,
}: {
error: Error & { digest?: string }
retry: () => void
}) {
useEffect(() => {
console.error(error)
// Send diagnostic information to
// your monitoring service if needed.
}, [error])
return (
<div role="alert">
<h2>Something went wrong</h2>
<p>
Please try again. If the problem continues,
contact support.
</p>
<button onClick={() => retry()}>
Try again
</button>
</div>
)
}

How does error.tsx work?

Next.js creates an error boundary around the relevant route segment. When an uncaught rendering error occurs inside that boundary, the fallback UI is displayed instead of the failed content.

You can create boundaries at different levels:

app/
├── error.tsx
├── dashboard/
│ ├── page.tsx
│ └── error.tsx
└── plants/
└── [slug]/
├── page.tsx
└── error.tsx

global-error.tsx

What happens if the root layout itself crashes?

The root app/error.tsx boundary cannot catch errors thrown by app/layout.tsx. For this case, Next.js provides global-error.tsx.

// app/global-error.tsx
'use client'
export default function GlobalError({
retry,
}: {
error: Error & { digest?: string }
retry: () => void
}) {
return (
<html lang="en">
<body>
<h2>Something went wrong</h2>
<p>
The application encountered an unexpected error.
</p>
<button onClick={() => retry()}>
Try again
</button>
</body>
</html>
)
}

Unlike an ordinary error boundary, global-error.tsx replaces the root layout. Therefore, it must provide its own <html> and <body> elements.

It also does not inherit the root layout’s global styles, fonts, or themes, so keep the fallback UI simple and self-contained.


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
Supabase: Clients in Next.js
October 30, 2026
2 min
Dev98

Dev98

React · Next.js · Web development