Next.js instrumentation.ts: How to Fix Request State Leaks in App Router Tracing
Next.js's instrumentation.ts file provides a single initialization point for distributed tracing and error reporting in the App Router, with its register() function running once per server instance rather than per request. The onRequestError hook, stable since Next.js 15, captures errors from Server Components, Route Handlers, Server Actions, and Middleware before Next.js renders its own error response. Vercel's Fluid Compute reuses warm server instances across concurrent requests, meaning any module-level variable used to store request-scoped state becomes shared mutable state that can leak between unrelated users' traces. Only AsyncLocalStorage-based context propagation — the mechanism the OpenTelemetry SDK already relies on — correctly isolates data to a single request. The @vercel/otel package simplifies OpenTelemetry SDK setup by handling exporter selection and span processor configuration behind a single registerOTel() call, reducing boilerplate significantly.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in