Error Handling in Next.js: From Development to Production
Back to Blog

Error Handling in Next.js: From Development to Production

March 21, 20262 min read44 views

Good error handling is invisible to users but invaluable to developers. When something goes wrong, users should see a helpful message while developers get the information they need to fix the issue. Next.js provides powerful primitives for this, but building a comprehensive error handling strategy requires understanding how these pieces fit together.

Error Boundaries: error.tsx and global-error.tsx

Next.js uses React Error Boundaries under the hood, exposed through special error.tsx files. These catch errors in their child component tree and display fallback UI instead of crashing the entire application.

"use client";

import { useEffect } from "react";

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    console.error("Application error:", error);
  }, [error]);

  return (
    <div>
      <h2>Something went wrong</h2>
      <button onClick={reset}>Try again</button>
    </div>
  );
}

For errors that affect the root layout, you need global-error.tsx, which must include its own <html> and <body> tags.

Handling Server Action Errors

Server Actions require a result type that distinguishes success from failure:

type ActionResult<T> = 
  | { success: true; data: T }
  | { success: false; error: string };

async function safeAction<T>(action: () => Promise<T>): Promise<ActionResult<T>> {
  try {
    const data = await action();
    return { success: true, data };
  } catch (error) {
    console.error("Server action error:", error);
    return { success: false, error: error.message };
  }
}

Client-Side Error Tracking

Production applications need error tracking that goes beyond console logs. Sentry provides error aggregation, stack traces, breadcrumbs, and alerting.

import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  sampleRate: 1.0,
  tracesSampleRate: 0.1,
});

User-Friendly Error Messages

Technical error messages frustrate users. Design error UX that provides helpful context without exposing implementation details. Create a mapping of error codes to friendly messages with appropriate actions.

Debugging Production Errors

Source maps let stack traces point to your original code. Breadcrumbs track user actions leading up to an error. Session replay lets you watch exactly what happened before an error.

A complete error handling architecture combines error boundaries, Server Action wrappers, error tracking, user-friendly messages, and debugging infrastructure. This ensures that when things go wrong—and they will—users see helpful messages and developers get actionable information.

Share this article