Observability in the Next.js App Router: Field Notes on instrumentation.ts, onRequestError, and the Trace That Leaked Across Requests
Next.js's instrumentation.ts file and its onRequestError hook give the App Router real distributed tracing and centralized error reporting, but Vercel Fluid Compute reusing one warm instance across concurrent requests means any request state stored outside OpenTelemetry's own context propagation — a module-level variable, a naive "current request" global — leaks between unrelated users'…
The Next.js App Router introduced server-side capabilities with React Server Components and standard Route Handlers. However, in production deployments on Vercel or AWS Lambda, API Route Handlers often experience significant serverless execution overhead. This includes cold starts, Node.js runtime parsing, and database connection latency. High costs and performance issues arise under heavy traffic.
To address this, the guide recommends edge-caching Next.js Route Handlers, bypassing Node.js runtime overhead on read requests, and achieving sub-15ms API response times. The bottleneck is standard Route Handlers, which execute on every single HTTP request, leading to high invocation bills.
The solution involves configuring Route Handlers to return Cache-Control headers and routing the API domain through an edge proxy (ApexCache). When an admin updates a product or a new order completes, trigger a background tag purge using Next.js Server Actions. This approach reduces production latency, warms up edge proxy caches, and slashes serverless function invocations by over 95%.
Production latency and cost comparisons show a significant improvement when using the Next.js Serverless Direct with Edge Proxy setup. API latency drops from 240ms to 11ms in the 50th percentile, while P99 latency improves dramatically. Serverless function invocations are reduced by 95.8%, and database connection pressure is minimal. The monthly Vercel or Cloud bills are slashed by over 75%.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.
This story
This is one outlet's version. Read the fullest account.