Next.js course Β· Module 6: Forms and Server Actions

error.tsx components for error handling

10 min read Β·
In this lesson9

When building Next.js applications, one important aspect is handling failure scenarios properly. The Next.js framework offers a simple yet powerful mechanism that allows easy isolation and handling of errors in an application - error.tsx components. In this module we'll look at how to effectively use these components to improve the resilience and user experience of our application.

What is the error.tsx component?

The error.tsx component is a special file in the Next.js application structure that acts as an "error boundary" for a given segment of the application. When an error occurs in that segment or its children:

  1. Next.js automatically catches the error
  2. Renders the error.tsx component instead of the component that produced the error
  3. Isolates the error to the specific segment, allowing the rest of the application to continue to work normally

How does error.tsx work in Next.js App Router?

In the App Router architecture, we can place error.tsx components at any level of the directory structure, which allows for very precise specification of error boundaries.

Basic implementation

Here's what a simple error.tsx component looks like:

'use client'; // Must be a client component

import { useEffect } from 'react';

interface ErrorComponentProps {
  error: Error & { digest?: string };
  reset: () => void;
}

export default function Error({ error, reset }: ErrorComponentProps) {
  useEffect(() => {
    // Optionally report the error to a monitoring service
    console.error('An unexpected error occurred:', error);
  }, [error]);

  return (
    <div className="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-md">
      <h2 className="text-xl font-bold text-red-600 mb-4">Something went wrong!</h2>
      <p className="text-gray-700 mb-4">
        Sorry, an unexpected error occurred. Our team has been notified.
      </p>
      <button
        onClick={reset}
        className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
      >
        Try again
      </button>
    </div>
  );
}

Key elements:

  1. 'use client' marker - the error.tsx component must be marked as a client component, even if the rest of the application uses server-side rendering.

  2. Props:

    • error: Error object containing information about what went wrong
    • reset: Function that allows retrying the render of the component that produced the error
  3. reset() function: Allows users to retry an operation without reloading the entire page.

Error handling strategies with error.tsx

1. Hierarchical error handling

Next.js allows you to create error.tsx components at various levels of the directory structure, enabling precise control over how errors are handled in different parts of the application.

app/
β”œβ”€β”€ error.tsx          # Global fallback for errors across the whole application
β”œβ”€β”€ layout.tsx
β”œβ”€β”€ page.tsx
β”œβ”€β”€ dashboard/
β”‚   β”œβ”€β”€ error.tsx      # Error handling for the entire dashboard
β”‚   β”œβ”€β”€ layout.tsx
β”‚   β”œβ”€β”€ page.tsx
β”‚   └── settings/
β”‚       β”œβ”€β”€ error.tsx  # Specific to the settings section
β”‚       └── page.tsx
└── profile/
    β”œβ”€β”€ error.tsx      # Specific to the user profile
    └── page.tsx

2. Detailed error messages in the development environment

We can adapt the error.tsx component to display more detailed error information in the development environment:

'use client';

export default function Error({ error, reset }) {
  const isDevelopment = process.env.NODE_ENV === 'development';

  return (
    <div>
      <h2>Something went wrong!</h2>

      {isDevelopment && (
        <div className="bg-gray-100 p-4 rounded my-4">
          <h3 className="font-bold">Error details (dev mode only):</h3>
          <p className="font-mono">{error.message}</p>
          <pre className="overflow-auto text-sm mt-2">{error.stack}</pre>
        </div>
      )}

      <button onClick={reset}>Try again</button>
    </div>
  );
}

3. Different error types, different messages

We can customize the look and messages depending on the error type:

'use client';

import { useEffect } from 'react';

export default function Error({ error, reset }) {
  // Logging the error to the monitoring system
  useEffect(() => {
    console.error(error);
    // logErrorToService(error);
  }, [error]);

  // Determine error type based on message or other properties
  const is404 = error.message?.includes('not found') || error.statusCode === 404;
  const isAuthentication = error.message?.includes('unauthorized') || error.statusCode === 401;

  return (
    <div className="p-6 mx-auto max-w-md">
      {is404 ? (
        <>
          <h2 className="text-xl font-bold">Resource not found</h2>
          <p>Sorry, the requested resource does not exist.</p>
        </>
      ) : isAuthentication ? (
        <>
          <h2 className="text-xl font-bold">Authentication required</h2>
          <p>You must log in to access this resource.</p>
          <button className="mt-4 px-4 py-2 bg-blue-500 text-white rounded">
            Log in
          </button>
        </>
      ) : (
        <>
          <h2 className="text-xl font-bold text-red-600">Unexpected error</h2>
          <p>Sorry, an unexpected problem occurred.</p>
        </>
      )}

      <button
        onClick={reset}
        className="mt-4 px-4 py-2 bg-gray-200 rounded hover:bg-gray-300"
      >
        Try again
      </button>
    </div>
  );
}

Integration with error monitoring systems

In production applications, collecting error information is essential. error.tsx components can be integrated with external error monitoring systems such as Sentry, LogRocket, or New Relic:

'use client';

import { useEffect } from 'react';
import * as Sentry from '@sentry/nextjs';

export default function Error({ error, reset }) {
  useEffect(() => {
    // Send error information to Sentry
    Sentry.captureException(error);
  }, [error]);

  return (
    <div>
      <h2>Something went wrong!</h2>
      <p>Our team has been notified of the problem.</p>
      <button onClick={reset}>Try again</button>
    </div>
  );
}

Handling API and fetch errors

Errors during data fetching in Next.js components can be handled with error.tsx, but it's worth remembering a few nuances:

In server components

// app/products/page.tsx
async function getProducts() {
  const res = await fetch('https://api.example.com/products');

  if (!res.ok) {
    // This error will be caught by the nearest error.tsx
    throw new Error('Failed to fetch products');
  }

  return res.json();
}

export default async function ProductsPage() {
  const products = await getProducts();

  return (
    <div>
      <h1>Our products</h1>
      <ul>
        {products.map(product => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    </div>
  );
}

In client components

'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';

export default function ClientProductsPage() {
  const [products, setProducts] = useState([]);
  const [error, setError] = useState(null);
  const router = useRouter();

  useEffect(() => {
    async function fetchProducts() {
      try {
        const res = await fetch('/api/products');

        if (!res.ok) {
          throw new Error('Data fetch error');
        }

        const data = await res.json();
        setProducts(data);
      } catch (err) {
        setError(err.message);
        // Optionally - we can manually invoke the nearest error.tsx
        // throw err; // This will make Next.js use the nearest error.tsx
      }
    }

    fetchProducts();
  }, []);

  if (error) {
    return (
      <div className="p-4 bg-red-50 border border-red-200 rounded">
        <h2 className="text-red-600 font-bold">An error occurred</h2>
        <p>{error}</p>
        <button onClick={() => router.refresh()}>Refresh page</button>
      </div>
    );
  }

  return (
    <div>
      <h1>Products (Client)</h1>
      {/* ... */}
    </div>
  );
}

Good practices when working with error.tsx

  1. Appropriate granularity - use error.tsx at levels that provide meaningful error isolation, but don't create too many components.

  2. Useful messages - provide user-friendly messages and clear instructions for next steps.

  3. Recovery options - offer ways to recover from the situation, such as a "Try again" button (using the reset function).

  4. Tracking and monitoring - always log errors to monitoring systems so you can track and resolve issues.

  5. Testing - test various error scenarios to make sure your error boundaries respond correctly.

  6. Accessibility - ensure that error messages are also accessible to users of assistive technologies.

Catching errors from layout.tsx

Error boundaries from error.tsx do not catch errors from layout.tsx components in the same segment. To handle errors in layouts, you must create an error.tsx component in the parent segment.

app/
β”œβ”€β”€ dashboard/
β”‚   β”œβ”€β”€ layout.tsx  // Errors here are NOT caught by error.tsx at the same level
β”‚   β”œβ”€β”€ error.tsx   // This will not catch errors from layout.tsx
β”‚   └── page.tsx

Correct structure for catching errors from layout.tsx:

app/
β”œβ”€β”€ error.tsx     // This will catch errors from dashboard/layout.tsx
β”œβ”€β”€ dashboard/
β”‚   β”œβ”€β”€ layout.tsx
β”‚   └── page.tsx

Example of a complete implementation

Below is an example of a more advanced error.tsx component that handles various error types, recovery options, and integration with an external monitoring system:

'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';

// Error types that we can handle specially
enum ErrorType {
  NOT_FOUND = 'NOT_FOUND',
  UNAUTHORIZED = 'UNAUTHORIZED',
  FORBIDDEN = 'FORBIDDEN',
  TIMEOUT = 'TIMEOUT',
  SERVER_ERROR = 'SERVER_ERROR',
  UNKNOWN = 'UNKNOWN'
}

interface ErrorComponentProps {
  error: Error & {
    digest?: string;
    statusCode?: number;
  };
  reset: () => void;
}

export default function Error({ error, reset }: ErrorComponentProps) {
  const router = useRouter();
  const [errorType, setErrorType] = useState<ErrorType>(ErrorType.UNKNOWN);
  const [isReporting, setIsReporting] = useState(false);

  // Determine the error type
  useEffect(() => {
    if (error.message?.toLowerCase().includes('not found') || error.statusCode === 404) {
      setErrorType(ErrorType.NOT_FOUND);
    } else if (error.message?.toLowerCase().includes('unauthorized') || error.statusCode === 401) {
      setErrorType(ErrorType.UNAUTHORIZED);
    } else if (error.message?.toLowerCase().includes('forbidden') || error.statusCode === 403) {
      setErrorType(ErrorType.FORBIDDEN);
    } else if (error.message?.toLowerCase().includes('timeout') || error.message?.includes('timed out')) {
      setErrorType(ErrorType.TIMEOUT);
    } else if (error.statusCode >= 500 && error.statusCode < 600) {
      setErrorType(ErrorType.SERVER_ERROR);
    }
  }, [error]);

  // Error reporting
  useEffect(() => {
    // Logging to console in dev
    console.error('Application error:', error);

    // In a real application, we would send this to an external service
    async function reportError() {
      try {
        setIsReporting(true);
        // Example implementation
        // await fetch('/api/error-reporting', {
        //   method: 'POST',
        //   headers: { 'Content-Type': 'application/json' },
        //   body: JSON.stringify({
        //     message: error.message,
        //     stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
        //     url: window.location.href,
        //     type: errorType,
        //     timestamp: new Date().toISOString()
        //   })
        // });
        await new Promise(resolve => setTimeout(resolve, 1000)); // Simulation
      } catch (e) {
        console.error('Failed to report error:', e);
      } finally {
        setIsReporting(false);
      }
    }

    reportError();
  }, [error, errorType]);

  // Render different messages depending on the error type
  function renderErrorContent() {
    switch (errorType) {
      case ErrorType.NOT_FOUND:
        return (
          <>
            <h2 className="text-2xl font-bold text-gray-800 mb-3">Resource not found</h2>
            <p className="text-gray-600 mb-4">
              The page you're looking for doesn't exist or has been moved.
            </p>
            <div className="flex space-x-4">
              <button
                onClick={() => router.back()}
                className="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300"
              >
                Back
              </button>
              <Link href="/" className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
                Home page
              </Link>
            </div>
          </>
        );

      case ErrorType.UNAUTHORIZED:
        return (
          <>
            <h2 className="text-2xl font-bold text-gray-800 mb-3">Login required</h2>
            <p className="text-gray-600 mb-4">
              You must log in to access this page.
            </p>
            <Link
              href="/login"
              className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
            >
              Log in
            </Link>
          </>
        );

      case ErrorType.FORBIDDEN:
        return (
          <>
            <h2 className="text-2xl font-bold text-gray-800 mb-3">Access denied</h2>
            <p className="text-gray-600 mb-4">
              You don't have permission to access this page or resource.
            </p>
            <button
              onClick={() => router.back()}
              className="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300"
            >
              Back
            </button>
          </>
        );

      case ErrorType.TIMEOUT:
        return (
          <>
            <h2 className="text-2xl font-bold text-gray-800 mb-3">Request timed out</h2>
            <p className="text-gray-600 mb-4">
              The operation took too long. Check your internet connection and try again.
            </p>
            <button
              onClick={reset}
              className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
            >
              Try again
            </button>
          </>
        );

      case ErrorType.SERVER_ERROR:
        return (
          <>
            <h2 className="text-2xl font-bold text-gray-800 mb-3">Server error</h2>
            <p className="text-gray-600 mb-4">
              Sorry, an error occurred on the server side. Our team has been notified.
            </p>
            <button
              onClick={reset}
              className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
            >
              Try again
            </button>
          </>
        );

      default:
        return (
          <>
            <h2 className="text-2xl font-bold text-gray-800 mb-3">Something went wrong</h2>
            <p className="text-gray-600 mb-4">
              Sorry, an unexpected error occurred. {isReporting ? 'Reporting the issue...' : 'Our team has been notified.'}
            </p>
            <div className="flex space-x-4">
              <button
                onClick={reset}
                className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
              >
                Try again
              </button>
              <button
                onClick={() => router.refresh()}
                className="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300"
              >
                Refresh page
              </button>
            </div>
          </>
        );
    }
  }

  // Render for development mode - additional error info
  function renderDevModeInfo() {
    if (process.env.NODE_ENV !== 'development') return null;

    return (
      <div className="mt-8 p-4 bg-gray-100 rounded-lg border border-gray-300">
        <h3 className="text-sm font-bold uppercase text-gray-500 mb-2">
          Error info (dev mode only)
        </h3>
        <p className="font-mono text-sm mb-2">{error.message}</p>
        {error.digest && (
          <p className="font-mono text-xs text-gray-500 mb-2">Digest: {error.digest}</p>
        )}
        {error.stack && (
          <pre className="mt-2 p-2 bg-gray-800 text-gray-200 rounded overflow-x-auto text-xs">
            {error.stack}
          </pre>
        )}
      </div>
    );
  }

  return (
    <div className="min-h-[400px] flex flex-col items-center justify-center p-6">
      <div className="w-full max-w-md bg-white rounded-lg shadow-lg p-8 text-center">
        {renderErrorContent()}
        {renderDevModeInfo()}
      </div>
    </div>
  );
}

Summary

error.tsx components in Next.js are a powerful error handling tool that:

  1. Isolate errors to specific segments of the application
  2. Allow presenting user-friendly messages
  3. Enable attempting to recover without reloading the page
  4. Can be customized for different error types
  5. Allow integration with error monitoring systems

Thanks to them, you can build more resilient applications that elegantly handle failure scenarios, improving the overall user experience and reducing frustration caused by unexpected problems.

Code for this lesson: App.tsx
import React, { useState, Component, ReactNode } from 'react';

// Simulation of error.tsx in the Next.js App Router
// Every segment can have its own error boundary

// Simulated error boundary (like error.tsx in Next.js)
class ErrorBoundary extends Component<
  { children: ReactNode; fallback: (error: Error, reset: () => void) => ReactNode },
  { error: Error | null }
> {
  state: { error: Error | null } = { error: null };
  static getDerivedStateFromError(error: Error) { return { error }; }
  reset = () => this.setState({ error: null });
  render() {
    if (this.state.error) return this.props.fallback(this.state.error, this.reset);
    return this.props.children;
  }
}

// error.tsx component - displayed when an error occurs
function ErrorComponent({ error, reset }: { error: Error; reset: () => void }) {
  return (
    <div style={{
      background: '#3e1010', border: '1px solid #f44336', borderRadius: 8,
      padding: 16, margin: '8px 0'
    }}>
      <h3 style={{ color: '#f44336', margin: '0 0 8px' }}>error.tsx</h3>
      <p style={{ color: '#ffcdd2', fontSize: 13 }}>{error.message}</p>
      <button onClick={reset} style={{
        background: '#f44336', color: '#fff', border: 'none', borderRadius: 4,
        padding: '6px 12px', cursor: 'pointer', fontFamily: 'monospace', marginTop: 8
      }}>
        Try again (reset)
      </button>
    </div>
  );
}

// Component that can throw an error
function DangerousWidget({ label }: { label: string }) {
  const [shouldError, setShouldError] = useState(false);
  if (shouldError) throw new Error(`Error in component "${label}"!`);
  return (
    <div style={{ background: '#1a2744', borderRadius: 8, padding: 16, border: '1px solid #64ffda' }}>
      <h4 style={{ color: '#64ffda', margin: '0 0 8px' }}>{label}</h4>
      <p style={{ color: '#aaa', fontSize: 12 }}>This component works correctly.</p>
      <button onClick={() => setShouldError(true)} style={{
        background: '#ff5722', color: '#fff', border: 'none', borderRadius: 4,
        padding: '4px 10px', cursor: 'pointer', fontFamily: 'monospace', fontSize: 11
      }}>
        Trigger error
      </button>
    </div>
  );
}

export default function ErrorTsxDemo() {
  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
      <h1 style={{ color: '#64ffda' }}>error.tsx in Next.js</h1>
      <p style={{ color: '#888', fontSize: 13, marginBottom: 16 }}>
        Every segment can have its own error.tsx. The error is isolated - the rest of the app keeps working.
      </p>

      <div style={{ display: 'grid', gap: 12 }}>
        <div style={{ background: '#0d1117', borderRadius: 8, padding: 12 }}>
          <div style={{ color: '#888', fontSize: 11, marginBottom: 8 }}>app/dashboard/error.tsx</div>
          <ErrorBoundary fallback={(error, reset) => <ErrorComponent error={error} reset={reset} />}>
            <DangerousWidget label="Dashboard Widget" />
          </ErrorBoundary>
        </div>

        <div style={{ background: '#0d1117', borderRadius: 8, padding: 12 }}>
          <div style={{ color: '#888', fontSize: 11, marginBottom: 8 }}>app/profile/error.tsx</div>
          <ErrorBoundary fallback={(error, reset) => <ErrorComponent error={error} reset={reset} />}>
            <DangerousWidget label="Profile Widget" />
          </ErrorBoundary>
        </div>

        <div style={{ background: '#0d1117', borderRadius: 8, padding: 12 }}>
          <div style={{ color: '#888', fontSize: 11, marginBottom: 8 }}>app/settings/error.tsx (independent)</div>
          <ErrorBoundary fallback={(error, reset) => <ErrorComponent error={error} reset={reset} />}>
            <DangerousWidget label="Settings Widget" />
          </ErrorBoundary>
        </div>
      </div>
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. ARIA labels in forms help with:

  1. QuestionARIA labels in forms help with:

Useful articles