The error.js Convention

Gracefully isolate crashes without bringing down the whole app.

Next.js5 min readConcept 10 of 65

Graceful degradation

In any application, things will eventually fail. A database query might time out, or an API might return malformed data. When a React component throws an unhandled error, it typically crashes the entire webpage.

The error.js (or .tsx) file convention prevents this. It acts as a safety net, automatically displaying a custom fallback UI when something goes wrong inside its route segment.

Isolating the blast radius

The primary goal of error.js is isolation. If the dashboard analytics page crashes, the user shouldn't be met with a blank white screen.

Instead, the specific analytics section should show an error message, while the surrounding layout.js (the sidebar, the navigation, the header) remains completely functional, allowing the user to click away and recover.

The mandatory 'use client'

To use it, export a React component from an error.tsx file. Next.js will automatically wrap the route in a React <ErrorBoundary>.

Crucially, this file **MUST** include the 'use client' directive at the top. React Error Boundaries rely on client-side lifecycle methods to catch rendering errors, so they cannot be Server Components.

Isolating the Blast Radius

Click the button to force the Page to crash. Watch how the Error Boundary catches it, replacing only the inner content while the Layout survives untouched.

layout.tsx (Parent)
Active
<ErrorBoundary>
page.tsx
Analytics DashboardStatus: Running normally

Click Force Fatal Crash to simulate a bug in page.tsx. Notice how the error.tsx boundary immediately catches the explosion, preventing the entire page from going white. The parent layout.tsx remains fully alive and interactive!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Why must an error.js file include the 'use client' directive?
  2. 2If you place an error.js and a layout.js in the EXACT SAME folder, will the error.js catch errors thrown by that layout.js?

Remember this

  • error.js isolates crashes to a specific route segment.
  • It MUST be a Client Component ('use client').
  • It provides an error object and a reset() recovery function as props.
  • It does NOT catch errors in the layout.js of the exact same folder.

Done with this concept?

Mark it complete to track your progress. No login needed.