Back to Blog
Lesson 13 of the Next.js: Build Full-Stack Apps with the App Router course
Next.jsJuly 31, 20263 min read

Handling Errors with error.js in Next.js: A Practical Guide

Learn to implement error.js in Next.js to handle runtime failures gracefully. Build resilient error boundaries with reset functionality for better UX.

Next.jsError HandlingReactWeb DevelopmentDebugging
Close-up of PHP code on a monitor, highlighting development and programming concepts.

Previously in this course, we explored loading states with loading.js to handle asynchronous UI delays. While loading.js manages the "waiting" state, your application must also prepare for the "failing" state. In this lesson, we will implement error.js to create resilient boundaries that prevent your entire application from crashing when a component encounters an unexpected runtime error.

Understanding Error Boundaries from First Principles

In a standard React application, an unhandled error in a component tree can unmount the entire application, leaving the user with a blank screen. Next.js solves this by wrapping route segments in Error Boundaries.

When you define an error.js file, Next.js automatically wraps the route segment (the page.js and any nested components) in a React Error Boundary. If an error occurs during rendering or data fetching within that segment, React "catches" the error and displays the UI defined in your error.js file instead of crashing the browser.

Implementing error.js in Your Project

To implement an error boundary, create an error.js file in the same directory as your page.js. This file must be a Client Component because it uses React state to manage the error recovery process.

Here is a standard implementation for our blog:

TSX
CE9178">'use client'; // Required for error boundaries

import { useEffect } from CE9178">'react';

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    // Log the error to an external reporting service
    console.error(error);
  }, [error]);

  return (
    <div className="p-8 text-center">
      <h2 className="text-2xl font-bold text-red-600">Something went wrong!</h2>
      <p className="mt-2 text-gray-600">{error.message || "An unexpected error occurred."}</p>
      <button
        onClick={() => reset()}
        className="mt-4 px-4 py-2 bg-blue-600 text-white rounded"
      >
        Try again
      </button>
    </div>
  );
}

The reset Functionality

The reset function provided by Next.js is a powerful tool for managing errors and professional error handling in React. When the user clicks "Try again," Next.js will attempt to re-render the contents of the Error Boundary. If the error was caused by a temporary network glitch during a data fetch, this will trigger the fetch again, potentially resolving the issue without requiring a full page refresh.

Hands-on Exercise: Triggering a Test Error

To verify your error boundary, let's intentionally break a page in our project.

  1. Locate your blog post page (e.g., app/blog/[slug]/page.tsx).
  2. Inside your data-fetching function, throw an error:
    TSX
    async function getPost(slug: string) {
      throw new Error("Failed to load post data");
    }
  3. Create app/blog/[slug]/error.tsx using the code block provided above.
  4. Navigate to a blog post in your browser. You should see your custom error UI instead of the standard development error overlay.

Common Pitfalls to Avoid

  • Forgetting 'use client': error.js must be a Client Component. If you omit the directive, Next.js will throw a build-time error.
  • Handling Global Errors: error.js only handles errors in the segment it is located in (or its children). If you need to catch errors in your root layout (like the navigation bar), you must use global-error.js in the root app directory.
  • Over-catching: Don't wrap your entire application in one giant error.js file. Place them at the segment level (e.g., /blog, /admin) so that a failure in one section doesn't make the entire site unusable.

FAQ

Q: Does error.js catch errors in event handlers? A: No. React Error Boundaries do not catch errors in event handlers (like a button onClick function). You should use try/catch blocks inside those functions for node.js security and handling async errors.

Q: Can I use error.js to catch 404s? A: No, error.js is for runtime exceptions. Use not-found.js for handling resources that do not exist in your database.

Recap

By implementing error.js, you move from a fragile application to a robust one. We've learned that these boundaries isolate failures, allow for clean user feedback, and provide a path to recovery via the reset function. This approach ensures your debugging process is cleaner and your user experience remains stable even when things go wrong.

Up next: We will implement not-found.js to handle missing routes and provide helpful 404 pages.

Similar Posts