Error Handling in Next.js – Expected Errors, Uncaught Exceptions, and Error Boundaries

Next.js categorizes errors into expected errors and uncaught exceptions. This article explains how to handle form errors with useActionState, show custom 404 pages with notFound, and define error boundaries for unexpected exceptions. It also covers event handler errors, startTransition exceptions, and global error handling in the root layout.

expected errorerror boundaryuseActionStatenotFound

~3 دقیقه مطالعه · آخرین به‌روزرسانی ۳ آبان ۱۴۰۴

Types of Errors in Next.js


Errors fall into two categories:

  • Expected errors: e.g. form validation failures or failed fetch requests
  • Uncaught exceptions: unexpected bugs or crashes during rendering

Handling Expected Errors


In Server Functions


Use useActionState to handle form errors. Instead of throwing, return structured error messages:


// app/actions.ts
'use server'
export async function createPost(prevState, formData) {
  const title = formData.get('title')
  const content = formData.get('content')
  const res = await fetch('https://api.vercel.app/posts', {
    method: 'POST',
    body: { title, content },
  })
  if (!res.ok) {
    return { message: 'Failed to create post' }
  }
}

In Client Forms


// app/ui/form.tsx
'use client'
import { useActionState } from 'react'
import { createPost } from '@/app/actions'

const initialState = { message: '' }

export function Form() {
  const [state, formAction, pending] = useActionState(createPost, initialState)
  return (
    <form action={formAction}>
      <input name="title" required />
      <textarea name="content" required />
      {state?.message && <p>{state.message}</p>}
      <button disabled={pending}>Create Post</button>
    </form>
  )
}

In Server Components


Check fetch responses and conditionally render fallback UI:


// app/page.tsx
export default async function Page() {
  const res = await fetch('https://...')
  if (!res.ok) return 'There was an error.'
  return '...'
}

Custom 404 Pages


Use notFound() to trigger a 404 UI:


// app/blog/[slug]/page.tsx
import { getPostBySlug } from '@/lib/posts'

export default async function Page({ params }) {
  const post = getPostBySlug(params.slug)
  if (!post) notFound()
  return <div>{post.title}</div>
}

// app/blog/[slug]/not-found.tsx
export default function NotFound() {
  return <div>404 - Page Not Found</div>
}

Handling Uncaught Exceptions


Error Boundaries


Create an error.tsx file in a route segment to catch rendering errors:


// app/dashboard/error.tsx
'use client'
import { useEffect } from 'react'

export default function Error({ error, reset }) {
  useEffect(() => {
    console.error(error)
  }, [error])
  return (
    <div>
      <h2>Something went wrong!</h2>
      <button onClick={() => reset()}>Try again</button>
    </div>
  )
}

Event Handler Errors


Error boundaries don’t catch event handler errors. Use useState to store and display them:


// app/ui/button.tsx
'use client'
import { useState } from 'react'

export function Button() {
  const [error, setError] = useState(null)
  const handleClick = () => {
    try {
      throw new Error('Exception')
    } catch (reason) {
      setError(reason)
    }
  }
  if (error) return <p>Error occurred</p>
  return <button onClick={handleClick}>Click me</button>
}

startTransition Errors


Errors inside startTransition bubble to the nearest error boundary:


// app/ui/button.tsx
'use client'
import { useTransition } from 'react'

export function Button() {
  const [pending, startTransition] = useTransition()
  const handleClick = () =>
    startTransition(() => {
      throw new Error('Exception')
    })
  return <button onClick={handleClick}>Click me</button>
}

Global Error Handling


Use global-error.tsx in the root app directory to catch layout-level errors. Must include <html> and <body> tags:


// app/global-error.tsx
'use client'
export default function GlobalError({ error, reset }) {
  return (
    <html>
      <body>
        <h2>Something went wrong!</h2>
        <button onClick={() => reset()}>Try again</button>
      </body>
    </html>
  )
}

Conclusion


Next.js offers robust error handling tools. With useActionState, notFound(), error boundaries, and global-error.tsx, you can build resilient applications that gracefully recover from both expected and unexpected failures.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

ادامه

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

ادامه

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

ادامه

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

ادامه

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

ادامه

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

ادامه