Handle expected errors as application state. Use error boundaries to recover from unexpected rendering failures.
Expected errors
Expected errors are normal outcomes of application logic. They should be handled explicitly and communicated clearly to users. Examples include:
Unexpected errors
Unexpected errors occur when the application cannot complete an operation as intended. Examples include:
These errors require logging, a safe fallback UI, and sometimes a retry mechanism.
useActionStateUse 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><inputid="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.
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.tsxexport 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.
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.tsximport Link from 'next/link'export default function NotFound() {return (<div><h2>Plant not found</h2><p>This plant may have been removedor the link may be incorrect.</p><Link href="/plants">Browse all plants</Link></div>)}
error.tsx as a Route-Level Error BoundaryThe 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
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.