Lesson 25 of 27Production Next.js
Observability and Running Next.js in Production
Instrument a Next.js app with logs, traces and error reporting, then run it on your own servers without stale caches, version skew or dropped work.
It is 2 a.m. and the on-call alert says checkout errors are up. A customer has sent a screenshot of your error page: "Something went wrong. Digest: 2841067395". Your logs contain thousands of lines with no request IDs, half your containers were replaced by a rolling deploy ten minutes ago, and some users report prices that changed yesterday. Every one of these is a known Next.js production problem with a known fix. Deploying Next.js showed you the basics of instrumentation.ts and multi-instance caching; this lesson goes deeper: how to see what your app is doing, and how to run it on your own infrastructure without the failures that only appear at scale.
Logs, traces and errors
Observability means you can answer new questions about production without shipping new code. Three signals do the work:
- Logs say what happened: one structured line per event, with a request ID so you can follow one request.
- Traces say where the time went: a tree of timed spans for one request (render, each
fetch, each database query), linked across services. - Errors say what broke: exception, stack trace, release, route and user context, grouped so one bug is one issue.
Metrics (request rate, error rate, latency percentiles) usually come from your host, load balancer or trace backend. In Next.js the hooks for all of this live in two files: instrumentation.ts for the server and instrumentation-client.ts for the browser.
instrumentation.ts in depth
instrumentation.ts (in the project root, or in src/) exports two optional functions. register() runs once when each server instance starts, before it handles requests. onRequestError() runs whenever the server catches an error while rendering, running a Route Handler, executing a Server Action or running proxy.
Next.js calls register() in every server runtime it uses, so guard Node-only SDKs with NEXT_RUNTIME, and import them dynamically so they are not bundled where they cannot run:
import type { Instrumentation } from "next";
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
await import("./instrumentation.node"); // OpenTelemetry SDK, Sentry, DB pool warm-up
}
}
export const onRequestError: Instrumentation.onRequestError = async (error, request, context) => {
const err = error as Error & { digest?: string };
console.error(
JSON.stringify({
level: "error",
msg: err.message,
digest: err.digest, // matches the code shown on the user's error page
method: request.method,
path: request.path,
routePath: context.routePath, // "/products/[id]", not "/products/123"
routeType: context.routeType, // "render" | "route" | "action" | "proxy"
routerKind: context.routerKind, // "App Router" | "Pages Router"
revalidateReason: context.revalidateReason, // set during background revalidation
}),
);
};The context object is what makes this better than a try/catch. routePath groups errors by route pattern rather than by thousands of URLs. routeType tells you whether the failure was a page render, an API handler, an action or proxy. revalidateReason flags errors that happened during a background ISR or use cache revalidation, which no user saw but which leave a stale page in place.
See why grouping by route pattern matters when you read an error log:
Press Run (⌘ Enter) to see what happens.Grouped by URL, the product page looks like three small problems. Grouped by route pattern, it is one bug causing 80% of errors, and the checkout failure is clearly a separate one in a Server Action.
The digest. In production, Next.js does not send a Server Component's error message to the browser, because it might contain secrets or SQL. The user's error.tsx receives a generic message and an error.digest, a hash that also appears on the server-side error. Show the digest on your error page ("Reference: 2841067395"), log it in onRequestError, and support can go from a customer screenshot to the exact stack trace in one search.
error.tsx shows error.message to users, but it always says something generic like 'An error occurred in the Server Components render'. How do you find the real error?instrumentation-client.ts
The browser counterpart is instrumentation-client.ts. It runs after the HTML loads and before React hydrates, so it is the place to start client error tracking, performance marks and analytics. It can also export onRouterTransitionStart(url, navigationType), which fires at the start of every App Router navigation: a clean hook for tracking client-side page views and timing navigations. Keep it small, since it runs before your app is interactive and adds to every page.
Traces with OpenTelemetry
Next.js is already instrumented with OpenTelemetry (OTel): once you register an SDK, it emits spans for the request (GET /products/[id]), the route render, every fetch from Server Components, Route Handler execution and generateMetadata. The simplest setup is @vercel/otel, which works on Vercel and on your own servers:
import { registerOTel } from "@vercel/otel";
registerOTel({
serviceName: "shop-web",
// exporter settings usually come from env vars such as OTEL_EXPORTER_OTLP_ENDPOINT
});Point the exporter at any OTLP-compatible backend (Grafana Tempo, Honeycomb, Datadog, Jaeger). Set NEXT_OTEL_VERBOSE=1 to see more internal spans while debugging. Add your own spans around expensive work (a database call, a call to a pricing service) with the standard @opentelemetry/api tracer.
The real payoff is propagation. The trace context travels in the traceparent header on outgoing fetch calls, so when your FastAPI or Go backend is also instrumented, one trace shows the browser request, the Next.js render and the backend query as a single timeline.
Next.js starts a root span GET /orders/[id] with a new trace ID.
Structured logs and after()
console.log("order created", order) is fine on a laptop and useless across forty containers. Log one JSON object per line with a fixed set of fields: level, msg, requestId (or the trace ID), route, userId (an ID, never an email), durationMs. Your log platform can then filter and aggregate. A library like pino does this fast. Never log request bodies, cookies, tokens or personal data by default; logs are copied to many places and kept for a long time.
Logging and analytics should not slow the user down. after() from next/server schedules work to run after the response has finished streaming:
"use server";
import { after } from "next/server";
import { headers } from "next/headers";
export async function placeOrder(formData: FormData) {
const order = await createOrder(formData); // the user waits for this
after(async () => {
const ua = (await headers()).get("user-agent"); // allowed in actions and handlers
await analytics.track("order_placed", { orderId: order.id, ua });
await audit.log({ action: "order.create", orderId: order.id });
});
return { ok: true, orderId: order.id };
}Some details that come up in code review:
aftercallbacks run even if the response failed: after a thrown error,notFound()orredirect(). That makes them good for audit logs and timing.- In Server Actions and Route Handlers you can call
cookies()andheaders()inside the callback. In a Server Component you cannot; read the values during render and use them inside the callback. afterdoes not make a route dynamic. In a static page its callback runs at build or revalidation time, not per visit.- It runs within the route's maximum duration on serverless platforms, so it is for short follow-up work. A job that takes minutes belongs in a queue.
What does this print?
const log: string[] = [];
const afterTasks: (() => void)[] = [];
const after = (fn: () => void) => afterTasks.push(fn);
function handle() {
log.push("save order");
after(() => log.push("send analytics"));
log.push("render page");
return "response";
}
const res = handle();
log.push("stream " + res);
afterTasks.forEach((fn) => fn());
console.log(log.join(" > "));Error tracking and source maps
An error tracker such as Sentry adds what logs lack: grouping, alerting, release tracking and readable stack traces from both server and browser. The Next.js SDK (@sentry/nextjs) hooks into instrumentation.ts, instrumentation-client.ts and onRequestError, and wraps your config with withSentryConfig in next.config.ts. Its setup wizard creates these files for you.
Production JavaScript is minified, so a raw browser stack trace reads a.js:1:48213. Source maps translate it back to checkout-form.tsx:42. Generate them during the build and upload them to the error tracker from CI, tagged with the release (use the git SHA). Do not publish them on your public site: leave productionBrowserSourceMaps off and delete the .map files from the deployed output after upload, so you do not hand your source code to anyone who asks.
Tag every event with the same release ID you use for your deployment. "This error started in release a1b2c3d" is the fastest route to the pull request that caused it.
Running your own servers at scale
A single next start process on one VM supports every feature. Problems appear when you run many instances behind a load balancer and replace them during rolling deploys. Here is the checklist teams learn the hard way.
1. Build once, promote the same image. Build a output: "standalone" Docker image once per commit and run that same image in staging and production. If you rebuild per environment, every build gets a different build ID and different Server Action IDs.
2. Share the cache. The default cache is memory plus local disk, per instance. With several instances, configure cacheHandler (for ISR, prerendered pages and route caching) and cacheHandlers (for use cache and use cache: remote) backed by shared storage like Redis. A good handler serialises entries correctly, bounds its size, and coordinates tags across instances (the refreshTags hook), so a revalidateTag call on one pod invalidates the page on all of them. Set cacheMaxMemorySize: 0 if you do not want a per-instance memory layer in front of it.
3. One Server Actions key. Set NEXT_SERVER_ACTIONS_ENCRYPTION_KEY (a base64 AES key) at build time, identical for every instance, or a form encrypted by one pod fails on another with "Failed to find Server Action".
4. Handle version skew. During a rolling deploy, a browser loaded from version A navigates while the load balancer sends it to version B. Old JavaScript chunks are gone, action IDs have changed, and prefetched data does not match. Set deploymentId (for example from the git SHA). Next.js then tags asset URLs and navigation requests with it, and when the client and server disagree it does a hard navigation (a full page reload) instead of a broken client one. Keeping old static assets available on the CDN for a while after a deploy avoids missing-chunk errors for users who stay on a page.
5. Runtime vs build-time env vars. NEXT_PUBLIC_ values are inlined into JavaScript at build time, so one image cannot have different public values per environment; changing them means rebuilding. Server-only variables are read at runtime, but only when the code actually runs per request. A value read in a static page is frozen at build. Read per-environment values during dynamic rendering (after await connection() or another request-time API) when one image must serve several environments.
6. Stream end to end. nginx, load balancers and some cloud gateways buffer responses by default, which turns streaming and partial prerendering into "wait for everything". Turn buffering off (for nginx, the X-Accel-Buffering: no header) and verify with curl -N that the shell arrives before the slow parts.
7. Health checks and graceful shutdown. Add a cheap Route Handler such as /api/health for liveness, and a readiness check that confirms the app can reach its database and cache. On SIGTERM, next start stops accepting new requests, finishes in-flight ones and runs pending after() callbacks. Give it a drain period (10 to 30 seconds is the documented recommendation) before the orchestrator kills the container, and make sure Node is PID 1 or behind an init that forwards signals, as covered in Docker in Production.
A user loaded the page from v1 and now clicks a link. The deploy is halfway through.
Match each production symptom to its cause and fix.
Adapters and OpenNext
Not every platform runs a long-lived next start process. Serverless and edge platforms need the build output split into functions, static files and routing rules. The Adapter API, stable since Next.js 16.2 through the top-level adapterPath option (or the NEXT_ADAPTER_PATH environment variable), lets a platform hook into next build and receive a documented description of every route, function and asset. Vercel's own adapter is open source as a reference implementation. OpenNext is the community project that packages Next.js for AWS (Lambda and CloudFront) and Cloudflare; check its docs for which features each target supports, especially caching and partial prerendering.
The practical question in a design discussion is: "Do we need serverless scale-to-zero, or is a few containers with a shared Redis simpler?" For most company apps with steady traffic, containers are easier to reason about and to debug.
Order the steps of a safe self-hosted release.
- Tap the steps below in the right order.
With logs, traces and a safe release process in place, you can build, ship and run a Next.js app end to end. The project lesson next has you build a whole app with these pieces on your own machine.
- onRequestError
- An
instrumentation.tsexport called with the error, the request and a context (route path, route type, router kind) whenever the server catches an error. - digest
- A hash attached to production Server Component errors. Users see it instead of the message; logs use it to find the real error.
- after()
- A
next/serverfunction that runs a callback after the response finishes, for logging, analytics and audit work. - trace propagation
- Passing trace context (the
traceparentheader) to downstream services so one trace covers every hop of a request. - version skew
- A client running one build talking to a server running another during a deploy.
deploymentIdlets Next.js detect it and hard-navigate. - cache handler
- A pluggable storage backend for the Next.js cache, such as Redis, shared by all instances and coordinating tag invalidation.
- Adapter API
- A stable (16.2+) build hook, set with
adapterPath, that lets platforms turn Next.js output into their own functions and routing.