Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 72 ยท Configuration, Tooling and Testing

Debugging and Error Handling

Debug a Next.js app step by step: the dev overlay, hydration mismatch errors, server and browser logs, breakpoints, instrumentation.ts error reporting and build errors.

Sooner or later something in your Next.js app breaks, and the first challenge is knowing where to look. The code runs in at least three places: in the build, on the server for each request, and in the visitor's browser. An error message that appears in one place often has its cause in another. A hydration warning in the browser console is really about what the server rendered; a blank page in production is a stack trace you can only find in the server logs.

This lesson gives you a method. You will learn what the development overlay shows, why hydration mismatch errors happen and how to fix them, where each kind of log ends up, how to set breakpoints, how instrumentation.ts lets you report errors from the server, and how to read the build errors you will meet most. Real Next.js cannot run on this site, so its files are read-only. The live examples are stand-ins: a React program that reproduces a hydration mismatch with real React, and a Node program that imitates the error-reporting hook.

Where to look first

Terminal Server Component and handler errors, build output.
Browser console Client Component errors and hydration warnings.
Dev overlay Source-mapped stack for the error on screen.
Server logs The only place production errors appear.

Ask first: did it fail in the build, on the server or in the browser?

1 / 2

The development overlay

When you run next dev and something throws, Next.js covers the page with an error overlay. It shows the message, a stack trace mapped back to your source files (not the compiled output), the code frame around the failing line, and the Next.js and React versions. Click a frame to open it in your editor. A small indicator button in a corner of the page also reports compile problems and lets you open developer tools for the page. Treat the first line of the overlay as the real error and read the code frame before the long stack.

Two things to remember about the overlay:

  • It only exists in development. In production the visitor sees your error.tsx, global-error.tsx or the default error page (see loading.tsx, error.tsx and not-found.tsx), and Server Component error messages are hidden from the browser on purpose; the browser only receives an opaque digest.
  • Errors thrown in a Server Component happen on the server, so the full details are in your terminal, not the browser console. If the overlay is not enough, scroll the terminal where next dev runs.

Hydration mismatch errors

Hydration is the step where React takes the HTML the server sent and attaches event handlers to it. To do that safely, React renders your components again in the browser and expects the result to match the server's HTML. If it does not, React reports a hydration mismatch. In recent versions it throws away the mismatching part of the server HTML and renders it again on the client. Your page still works, but you paid for double rendering and the visitor may see a flash of changed content.

Typical causes:

  • Values that differ per render: Date.now(), new Date(), Math.random(), or a freshly generated id in the render body.
  • Browser-only checks: branches like typeof window !== "undefined", or reading localStorage or window.innerWidth while rendering.
  • Locale and time zone formatting: date.toLocaleString() on the server (maybe in UTC, English) and in the browser (the visitor's zone and language).
  • Invalid HTML nesting: a <div> or another <p> inside a <p>, a <tr> directly inside a <table> without <tbody> in some cases, or a link inside a link. The browser repairs the HTML while parsing, so the tree no longer matches React's.
  • Outside interference: browser extensions that inject elements or attributes into the page, or a CDN feature that rewrites HTML.

The cure is to make the first client render identical to the server render, then change things after hydration in an effect. The stand-in below uses real React 19 (the development build, which has the detailed messages). It renders a component to a string the way a server does, puts that HTML into the page, then calls hydrateRoot on it. A global flag plays the role of "am I on the server?". The first button hydrates a broken component; the second hydrates the fixed version.

Reproducing and fixing a hydration mismatch

With the broken component, the server HTML says "server", the first browser render says "browser", and React reports that the server-rendered text did not match; it then repairs the page, so the final text is correct but the error was real. With the fixed component the first client render also says "server" (the state's initial value), so hydration succeeds silently, and the effect then changes the text to "browser". The price of the fix is a brief moment of the neutral value, which is the honest cost of showing browser-only information.

Other tools for the same problem:

  • suppressHydrationWarning on a single element tells React not to complain about a text difference in that element's direct content, for example a timestamp. It hides one level only and is an escape hatch, not a fix.
  • For a widget that cannot render on the server at all, load it with next/dynamic and { ssr: false } inside a Client Component. It is not allowed in a Server Component.
  • Run your HTML through a validator when you see nesting warnings; the dev overlay's diff points at the tags involved.

Logging: who prints where

console.log inside a Server Component, Route Handler or Server Action prints in the terminal that runs Next.js (in production, to the process's standard output, which your host collects). console.log inside a Client Component prints in the browser console, and also on the server during the initial server render of that component, which is why a log line sometimes appears twice. Remembering that rule saves a lot of confusion.

In development you can ask Next.js to log every fetch made on the server, including cache hits, with a config option (read-only):

TypeScript
// next.config.ts (read-only)
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  logging: {
    fetches: { fullUrl: true },
  },
};

export default nextConfig;

For production, prefer structured logs: one JSON object per line with a level, a message and context fields (request path, user id, the error digest). Log platforms can search and alert on those. Never log secrets, full request bodies or whole process.env, and keep log levels meaningful so that "error" means someone should look.

Breakpoints

You are not limited to logs. Start the dev server with Node's inspector enabled and attach a debugger:

Terminal
# read-only
NODE_OPTIONS="--inspect" npm run dev

Then use Chrome's chrome://inspect page or your editor's "attach to Node process" feature. In VS Code you can save a launch configuration that starts npm run dev under the debugger, which lets you set breakpoints in Server Components, Route Handlers and Server Actions. Browser code is debugged in the browser's developer tools as usual; the source maps make breakpoints land in your TypeScript files.

Reporting errors with instrumentation.ts

In production nobody is watching the terminal, so you need errors to reach a tracker or at least a log you search. Next.js supports a file called instrumentation.ts (in the project root, or inside src/) with two exports:

TypeScript
// instrumentation.ts (read-only)
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    await import("./lib/error-reporter").then((m) => m.start());
  }
}

export async function onRequestError(
  error: { digest?: string } & Error,
  request: { path: string; method: string; headers: { [key: string]: string | string[] | undefined } },
  context: { routerKind: string; routePath: string; routeType: string },
) {
  const { report } = await import("./lib/error-reporter");
  report({ error, path: request.path, method: request.method, route: context.routePath });
}

register() runs once when a new server instance starts. It is the place to start an observability SDK, validate your environment variables (see Environment Variables and Secrets), or open connections. Because the same file is used by both the Node.js and the Edge runtime, check process.env.NEXT_RUNTIME before importing Node-only code. onRequestError() is called for every error the server catches while handling a request, with the error (including its digest), details of the request and context about where the error happened: which kind of router, which route pattern, and whether it came from rendering, a Route Handler, a Server Action or the proxy file. Error-tracking products such as Sentry use these two hooks under the hood.

The next example is a stand-in written in plain Node.js. It does not use Next.js, so the digest is computed by our own code and the "request" is a small object, but it shows the pipeline: the visitor gets a short generic response with a reference id, while the log receives the details, with sensitive headers removed.

Node.js A stand-in for onRequestError: log details, show a digest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice what each audience gets. The visitor's response contains only a status and a digest. The log line contains the message, the route pattern and the redacted headers, so you can search the digest from a user's bug report and land on the exact failure. Real Next.js does the same job for errors in Server Components, with the digest attached to the error that the browser's error.tsx receives.

Common build errors

next build is stricter than next dev, because it renders every static page and type-checks the project. These problems come up again and again:

What you see (roughly) Usual cause Fix
A message that a hook such as useState only works in a Client Component A component with state, effects or event handlers has no "use client", or is imported into a Server Component Add "use client" to the smallest component that needs it (Client Components)
useSearchParams() should be wrapped in a Suspense boundary A client component reads search params during static prerendering Wrap it in <Suspense>, or make the page dynamic
Module not found: Can't resolve 'fs' (or path, net) Node-only code reached a Client Component bundle Move the code to a Server Component or action; add import "server-only" to catch it early
Error occurred prerendering page /x The page throws while being generated at build time (missing data, a missing environment variable) Read the error shown above the message; fix the data or env var, or make the page dynamic
params should be awaited before using its properties Code from before version 15 uses params.slug directly const { slug } = await params
A type error naming a page or route file A wrong prop type or an invalid export from a page.tsx or route.ts file Fix the type; only the documented exports are allowed from special files
A dynamic server usage message for a route A static page calls cookies(), headers() or reads searchParams Accept the dynamic route, or remove the dynamic call (Static vs Dynamic Rendering)

Always scroll up to the first error in the output. Later lines are often consequences. If a build passes locally and fails on the host, compare Node versions, environment variables and whether the host runs npm ci from the lockfile.

A debugging routine

  1. Reproduce it with the smallest steps, and note whether it happens in next dev, in a production build (next build && next start), or both.
  2. Decide where it ran: terminal output means server or build; browser console means client.
  3. Read the first line of the message and the source-mapped frame in your own code.
  4. Make a hypothesis and test it with a log line or a breakpoint, not by changing five things at once.
  5. After fixing, write a test (see Testing Next.js Apps) so the bug stays fixed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Server Component throws an error. Where can you read the full message and stack in production?

    Next.js hides details of server errors from the browser. The server's standard output (or your error tracker) has the full message, and the digest links the two.
  2. 2. Which code causes a hydration mismatch?

    The server and the browser render at different moments and get different values, so the HTML no longer matches. Effects run only after hydration, so they are safe.
  3. 3. What does register() in instrumentation.ts do?

    register() is called once per server start. onRequestError() is the hook called for each request error.
  4. 4. A build fails with Module not found: Can't resolve 'fs'. What is the most likely cause?

    fs exists only on the server. If a Client Component imports a module that uses it, the browser bundle cannot resolve it.
  5. 5. Where does console.log inside an async Server Component print?

    Server Components run on the server, so their output goes to the process's standard output.

Summary

  • First decide where the problem happened: build, server or browser; terminal output and browser console show different halves of the story.
  • The dev overlay shows a source-mapped stack in development only; in production, errors from the server reach the browser as a digest.
  • Hydration mismatches come from non-deterministic render output, browser-only checks, locale differences and invalid HTML nesting; make the first client render match the server, then change in useEffect.
  • Use structured logs, never log secrets, and attach a debugger with NODE_OPTIONS="--inspect" when logs are not enough.
  • instrumentation.ts exports register() (once at startup) and onRequestError() (every caught request error) for monitoring.
  • Read the first build error, and check Node version and environment variables when a build passes locally but fails on the host.

Next: Building and Deploying