Next.js

Error Handling

Handling runtime errors, global errors, and not found pages in Next.js App Router.

Error Boundary: The `error.js` file convention allows you to gracefully handle runtime errors in nested routes.
📄app/error.tsx
TSX
'use client' // Error components 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>
  )
}
Global Error: `global-error.js` wraps the entire application, acting as a fallback for the root layout.
📄app/global-error.tsx
TSX
'use client' // Global error components must be Client Components
 
export default function GlobalError({
  error,
  reset,
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  return (
    // global-error must include html and body tags
    <html>
      <body>
        <h2>Something went wrong globally!</h2>
        <button onClick={() => reset()}>Try again</button>
      </body>
    </html>
  )
}
Not Found: The `not-found.js` file is used to render a custom UI when the `notFound()` function is thrown within a route segment.
📄app/not-found.tsx
TSX
import Link from 'next/link'
 
export default function NotFound() {
  return (
    <div>
      <h2>Not Found</h2>
      <p>Could not find requested resource</p>
      <Link href="/">Return Home</Link>
    </div>
  )
}