What is the error.js file used for?
error.js defines an error boundary for a route segment. If anything in that segment's page or nested children throws while rendering, Next.js shows your error component instead, while the parent layouts keep working. It must be a Client Component.
Props
error: the thrown value. Server errors arrive with a generic message in production and anerror.digesthash you can match in server logs. Narrow it withinstanceof Error.retry()(stable since 16.3): re-fetches and re-renders the boundary's children inside a transition. Use this in most cases, because it recovers from Server Component errors.reset(): only clears the error state and re-renders on the client without re-fetching.
Scope
error.tsxwrapsloading,not-found,pageand nested layouts in its segment, but not thelayout.tsxof the same segment. An error in a layout is caught by the parent segment's error file.global-error.tsxinapp/catches errors in the root layout. It replaces the whole document, so it must render<html>and<body>.notFound()andredirect()are not treated as errors.
Component-level boundaries
catchError from next/error (stable in 16.3) creates an error boundary component you can wrap around any part of the tree, with the same retry() behavior and correct handling of notFound() and redirect().
Good practice
Report errors to monitoring in useEffect, or centrally with onRequestError in instrumentation.ts. Do not show raw error messages to users. Expected failures such as validation errors should be returned as values, not thrown.
Code example
1// app/dashboard/error.tsx2"use client";34import { useEffect } from "react";56export default function DashboardError({7 error,8 retry,9}: {10 error: Error & { digest?: string };11 retry: () => void;12}) {13 useEffect(() => {14 // Send to Sentry, Datadog, etc. digest matches the server log entry15 console.error("Dashboard failed", error.digest, error);16 }, [error]);1718 return (19 <div role="alert">20 <h2>Something went wrong loading your dashboard.</h2>21 <button onClick={() => retry()}>Try again</button>22 </div>23 );24}2526// Component-level boundary anywhere in the tree:27// "use client";28// import { catchError, type ErrorInfo } from "next/error";29// function Fallback(props: {}, { retry }: ErrorInfo) {30// return <button onClick={() => retry()}>Reload widget</button>;31// }32// export default catchError(Fallback);
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.