Next.js is already instrumented. The framework creates OpenTelemetry spans for every request, render, route handler and fetch call. What it does not include is an SDK to export them. Your job is to register one in instrumentation.ts, and there are two ways to do it.
Key takeaways
instrumentation.tsgoes in the project root, or insrc/if you use one. Next.js calls itsregister()once per server start.@vercel/otelis the short path and runs in both runtimes.@opentelemetry/sdk-nodeis Node.js only and must sit behind aNEXT_RUNTIME === "nodejs"check.- Neither setup sends
traceparenton outgoingfetchcalls to your own APIs until you configure it. - Server Actions have no span of their own. They run inside the page's
POSTrequest span.
Quick start
The shortest working setup is one package, one file and three variables.
npm install @vercel/otel @opentelemetry/api instrumentation.ts
import { registerOTel } from "@vercel/otel";
export function register() {
registerOTel({ serviceName: "storefront" });
} .env
OTEL_EXPORTER_OTLP_ENDPOINT="https://otlp.example.com"
OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_KEY"
The file goes in the project root, or in src/ if you use one. Start the app, make a request, and within about 5 seconds a batch of spans is posted to /v1/traces on that endpoint.
How tracing works in Next.js
This section explains where the SDK plugs in. Next.js has calls to the OpenTelemetry API built into its server. With no SDK registered they do nothing. Once register() installs one, the same calls produce spans.
Next.js creates the spans. The SDK you register decides where they go.
- The file.
instrumentation.ts(or.js) exports a function namedregister. Next.js runs it once per server start, before any request. - The location. Project root, next to
next.config.ts, orsrc/if yourapporpagesdirectory lives there. Never insideapp. - Dev mode.
register()also runs innext dev. - Versions. Stable and on by default since Next.js 15. On 13.4 and 14 you turn it on:
next.config.js
// next.config.js, Next.js 13.4 and 14 only
module.exports = {
experimental: { instrumentationHook: true },
}; Configure @vercel/otel
This is the package from the quick start, with the options most apps need. @vercel/otel wraps the OpenTelemetry SDK, works on any host despite the name, and is the only option that runs in the Edge runtime.
With no exporter in code, it builds an OTLP exporter from the environment. Outside Vercel, OTEL_EXPORTER_OTLP_ENDPOINT is all that tells it where to send spans.
instrumentation.ts
import { registerOTel } from "@vercel/otel";
export function register() {
registerOTel({
serviceName: "storefront",
attributes: {
"deployment.environment.name": process.env.DEPLOY_ENV ?? "development",
"service.version": process.env.GIT_SHA ?? "dev",
},
instrumentationConfig: {
fetch: {
// traceparent is only sent to URLs listed here
propagateContextUrls: [/^https:\/\/api\.example\.com/],
},
},
});
} attributes is merged over the defaults the package sets itself: node.env, process.runtime.name and cloud.provider=vercel, the last one even when you self-host. On Vercel it also fills the deployment environment, region and git SHA.
Setup with the OpenTelemetry Node SDK
This is the alternative for apps that run on Node.js only. @opentelemetry/sdk-node gives you library instrumentations, your own span processors, and the same setup code as your other Node.js services.
npm install @opentelemetry/api @opentelemetry/sdk-node \
@opentelemetry/exporter-trace-otlp-http \
@opentelemetry/instrumentation-undici \
@opentelemetry/resources @opentelemetry/semantic-conventions
Next.js compiles instrumentation.ts for every runtime the app uses, and the SDK imports Node.js modules. So the entry file only checks the runtime and loads the SDK from a second file:
instrumentation.ts
export async function register() {
// The Node SDK cannot load in the Edge runtime, so import it conditionally.
if (process.env.NEXT_RUNTIME === "nodejs") {
await import("./instrumentation.node");
}
} instrumentation.node.ts
import { NodeSDK } from "@opentelemetry/sdk-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { UndiciInstrumentation } from "@opentelemetry/instrumentation-undici";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic-conventions";
const sdk = new NodeSDK({
resource: resourceFromAttributes({
[ATTR_SERVICE_NAME]: "storefront",
[ATTR_SERVICE_VERSION]: process.env.GIT_SHA ?? "dev",
"deployment.environment.name": process.env.DEPLOY_ENV ?? "development",
}),
// Endpoint and headers come from OTEL_EXPORTER_OTLP_* variables.
traceExporter: new OTLPTraceExporter(),
// Client spans for fetch() plus traceparent on outgoing requests.
instrumentations: [new UndiciInstrumentation()],
});
sdk.start(); - The guard is required. Next.js replaces
process.env.NEXT_RUNTIMEat build time and drops the dead branch. That keeps the SDK out of the Edge bundle. A top-levelimport "./instrumentation.node"defeats it. - Use
resourceFromAttributes. Older tutorials usenew Resource(...), which was removed in version 2 of the SDK packages. - No endpoint in code. The exporter reads the same
OTEL_EXPORTER_OTLP_*variables as the quick start.
| @vercel/otel | @opentelemetry/sdk-node | |
|---|---|---|
| Runtimes | Node.js and Edge | Node.js only |
| Runtime guard needed | No | Yes |
Outgoing fetch | Built-in fetch instrumentation | @opentelemetry/instrumentation-undici |
traceparent sent by default | Only to Vercel deployment URLs | To every host, once undici instrumentation is on |
| Library instrumentations | Accepts them through instrumentations | Full set |
| Resource detection | Vercel and runtime attributes | Host, OS and process attributes |
Running a custom Express server? See OpenTelemetry for Express.
Pick one. As of November 2026 they do not share dependency versions: @vercel/otel 2.3 expects the 2.x SDK packages, and sdk-node 0.301 is built on the 3.x line. Installing both ends in peer dependency conflicts.
Node.js vs Edge runtime
This section tells you whether the Edge runtime affects your choice. Code runs on Node.js unless a file exports runtime = "edge". Next.js sets NEXT_RUNTIME to nodejs or edge and calls register() separately in each.
- Node.js runtime. Both setups work. A long-running server batches and exports spans in the background.
- Edge runtime. Only
@vercel/otelworks. In a test with one Edge route handler it exported that route's spans as a separate batch withprocess.runtime.name=edge. With the manual setup and the guard, Edge code produces no spans.
Next.js 16.4 prints The Edge Runtime is deprecated for any route that opts in, and middleware (proxy.ts in Next.js 16) runs on Node.js by default. With no runtime = "edge" export, either setup covers the whole app.
The spans Next.js emits itself
This section shows what you get before writing any tracing code. Below is one real request to a route handler behind a proxy.ts, with one custom span and one fetch, as exported by the Node SDK setup.
Seven of these nine spans come from Next.js, and only load-order was written by hand. Three module-loading spans are left out.
Every span in the next.js scope carries next.span_type, the internal operation name. The routed server span is the one to build dashboards on:
name: GET /products/[slug]
kind: SERVER
next.span_type: BaseServer.handleRequest
http.method: GET
http.route: /products/[slug]
http.target: /products/blue-shirt
http.status_code: 200
next.route: /products/[slug] - Route templates, not URLs. The name and
http.routeuse/products/[slug], so every product page lands in one group. The concrete path is inhttp.target. - Older HTTP attribute names. Next.js emits
http.methodandhttp.status_code, nothttp.request.methodandhttp.response.status_code.
Span names for App Router, Route Handlers and Server Actions
| What ran | Span name | next.span_type |
|---|---|---|
| Any matched request | GET /products/[slug] | BaseServer.handleRequest |
| Server Components render | render route (app) /products/[slug] | AppRender.getBodyResult |
generateMetadata | generateMetadata /products/[slug]/page | ResolveMetadata.generateMetadata |
| Route handler | executing api route (app) /api/orders/[id] | AppRouteRouteHandlers.runHandler |
| Server Action | POST /products/[slug] (the page's request span) | BaseServer.handleRequest |
| Middleware or proxy | middleware GET | Middleware.execute |
Server-side fetch | fetch GET https://api.example.com/stock | AppRender.fetch |
| Pages Router data | getServerSideProps /route, getStaticProps /route | Render.getServerSideProps, Render.getStaticProps |
| Pages Router API route | executing api route (pages) /api/route | Node.runHandler |
- Server Components are one span. The whole React render is
render route (app) .... Components get no spans of their own, so slow data loading only shows through itsfetch, database or custom spans. - Server Actions are a POST to the page. An action called from
/products/[slug]appears asPOST /products/[slug]with a full page render underneath. No span carries the action's name. - Middleware adds a second server span. With a matching
proxy.tsormiddleware.ts, the trace root is a server span named onlyGET, as in the tree above. Group byhttp.route, not by root span name. Requests that match no route (404s) are also named justGET.
NEXT_OTEL_VERBOSE
Next.js only emits an allowlist of span types by default. NEXT_OTEL_VERBOSE=1 turns on the rest, such as BaseServer.render, AppRender.renderToReadableStream and LoadComponents.loadComponents. In the test app the same three requests went from 46 spans to 96. Leave it off in production.
fetch spans and trace propagation
This section explains why a downstream service can end up in a separate trace. Next.js wraps server-side fetch and creates a client span per call, but it does not add a traceparent header. Context propagation is the SDK's job.
Incoming context works out of the box in both setups. Outgoing context needs one of the two changes below.
- @vercel/otel replaces the Next.js fetch span with its own (scope
@vercel/otel/fetch) and setsNEXT_OTEL_FETCH_DISABLED=1for you. It injectstraceparentonly for Vercel deployment URLs. In the test, a call to another host arrived with no header until the host was added topropagateContextUrls. - The Node SDK needs
@opentelemetry/instrumentation-undici, because Node'sfetchis built on undici. It hooks in throughdiagnostics_channel, so it works on bundled server code, and it injectstraceparenton every outgoing request.
With the Node SDK each call then has two client spans, the Next.js one and its undici child. Set NEXT_OTEL_FETCH_DISABLED=1 to keep only the undici span, which owns the propagated ID.
Custom spans
This section adds your own steps to the trace. Start spans with the API package. The code is the same in both setups, in route handlers, Server Components and Server Actions:
app/api/orders/[id]/route.ts
import { SpanStatusCode, trace } from "@opentelemetry/api";
const tracer = trace.getTracer("checkout");
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const order = await tracer.startActiveSpan("load-order", async (span) => {
try {
span.setAttribute("order.id", id);
const res = await fetch("https://api.example.com/stock");
return { id, stock: await res.json() };
} catch (error) {
span.recordException(error as Error);
span.setStatus({ code: SpanStatusCode.ERROR });
throw error;
} finally {
span.end();
}
});
return Response.json(order);
} startActiveSpan makes the new span the parent of whatever runs inside the callback, so the fetch span nests under load-order. End the span in finally, or it is never exported.
When a new span is more than you need, add attributes to the active one. Inside a Server Action that is the page's request span:
app/actions.ts
"use server";
import { trace } from "@opentelemetry/api";
export async function createOrder(formData: FormData) {
// The active span is the POST request span of the page.
trace.getActiveSpan()?.setAttribute("order.sku", String(formData.get("sku")));
}
In the test run, order.sku landed on the POST /products/[slug] server span.
Database and client library spans
This section covers the spans Next.js does not create. Database drivers need the matching OpenTelemetry instrumentation in the instrumentations array. For PostgreSQL through pg:
npm install pg @opentelemetry/instrumentation-pg instrumentation.node.ts
import { PgInstrumentation } from "@opentelemetry/instrumentation-pg";
// in new NodeSDK({ ... })
instrumentations: [new UndiciInstrumentation(), new PgInstrumentation()],
In a production build this produced a pg.connect client span under the route handler span with no other changes. It worked because of a bundling detail:
- Instrumentations patch at load time. Most of them wrap a library when it is loaded with
require(). - Bundled libraries are never loaded that way. Next.js bundles server dependencies, so the patch never applies. You get no spans and no error.
- Some packages are left unbundled. The built-in list includes
pg,mongodb,mongoose,@prisma/client,expressandpino.
For anything not on the list, opt it out yourself:
next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
// Load these with require() at runtime instead of bundling them.
serverExternalPackages: ["mysql2", "ioredis"],
};
export default nextConfig; Logs with trace_id
This section links each log line to the trace it belongs to. The API package knows the active span anywhere in a request, so a logger can stamp every line without the caller passing anything. With Pino:
lib/logger.ts
import { trace } from "@opentelemetry/api";
import pino from "pino";
export const logger = pino({
// Runs on every log call and adds the active span's IDs.
mixin() {
const span = trace.getActiveSpan();
if (!span) return {};
const { traceId, spanId } = span.spanContext();
return { trace_id: traceId, span_id: spanId };
},
}); Calling logger.info({ orderId: id }, "loading order") inside the load-order span printed:
{"level":30,"time":1795912130445,"pid":77429,"hostname":"web-1","trace_id":"e3b75edb4128460b9b10ee7300d0c7b5","span_id":"0609e4248d7a5854","orderId":"42","msg":"loading order"} - The
span_idis the custom span's, not the request's, so the line points at the exact step. - A
mixinis a plain function call, so it works whether or not Next.js bundles the logger. The same lines work in aconsole.logwrapper. - Logs stay on stdout, where most log pipelines collect them. To ship them over OTLP instead, both
registerOTelandNodeSDKacceptlogRecordProcessors.
Browser to server trace continuity
This section joins a page load or click to the server work it caused. The browser and the server have to share a trace ID, and there are two directions.
Server to browser, for the first page load. No JavaScript has run yet, so there is no browser span to continue. Next.js can write the server's trace context into the document instead:
next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
experimental: {
// Writes <meta name="traceparent"> into server-rendered HTML.
clientTraceMetadata: ["traceparent", "tracestate"],
},
};
export default nextConfig; <meta name="traceparent" content="00-4bf92f3577b34da6a3ce929d0e0e4736-b8260c149d975d0a-01"/> A browser SDK reads that tag and attaches its page load span to the server's trace. The option is experimental and only meaningful on dynamically rendered pages.
Browser to server, for everything after. A browser tracing SDK, initialized in instrumentation-client.ts (Next.js 15.3 and later), adds traceparent to fetch calls. Same-origin requests to route handlers and Server Actions then continue the browser's trace. Cross-origin APIs need the header allowed in CORS.
Production configuration
This section lists what to set before real traffic. Both setups read the standard SDK environment variables, so none of it needs code changes:
.env.production
OTEL_SERVICE_NAME="storefront"
OTEL_RESOURCE_ATTRIBUTES="deployment.environment.name=production,service.version=1.42.0"
# Keep 10% of new traces, and follow the caller's decision when there is one
OTEL_TRACES_SAMPLER="parentbased_traceidratio"
OTEL_TRACES_SAMPLER_ARG="0.1"
# Batch span processor (these are the defaults)
OTEL_BSP_SCHEDULE_DELAY="5000"
OTEL_BSP_MAX_EXPORT_BATCH_SIZE="512"
OTEL_BSP_MAX_QUEUE_SIZE="2048" - Resource attributes. Set
service.name,service.versionanddeployment.environment.nameat minimum. Values set in code win overOTEL_RESOURCE_ATTRIBUTES. - Sampling. The default keeps every trace, at around ten spans per request before your own.
parentbased_traceidratiokeeps a fixed share and respects an upstream caller's decision. The sampling guide covers keeping all errors and slow requests instead. - Batching. Spans go out every 5 seconds or 512 spans, which suits a long-running
next startserver or container. - Secrets. OTLP headers belong in server-only variables. A
NEXT_PUBLIC_prefix inlines the value into browser bundles. - Shutdown. The last batch is not flushed on
SIGTERMby default. In a test, a request followed bySIGTERMlost its spans in both setups, because Next.js exits before the batch timer fires.
With the Node SDK, take over signal handling and shut the SDK down yourself:
instrumentation.node.ts
// Needs NEXT_MANUAL_SIG_HANDLE=true, or Next.js exits before the flush ends.
if (process.env.NEXT_MANUAL_SIG_HANDLE) {
process.once("SIGTERM", async () => {
await sdk.shutdown();
process.exit(0);
});
} - Set
NEXT_MANUAL_SIG_HANDLE=truein the server's environment so Next.js leaves the signal to you. With both in place, the same test exported the request's spans before exit. - With
@vercel/otelon your own servers,registerOTelreturns no handle to flush, so a shorterOTEL_BSP_SCHEDULE_DELAYis the way to shrink the window. On Vercel the package flushes after each request throughwaitUntil.
Self-hosting vs Vercel. A self-hosted app, whether next start or an output: "standalone" build run with node server.js in Docker, is a long-running process. It reads the OTEL_* variables at runtime and exports batches in the background. In a test, the standalone server exported the same spans and flushed on SIGTERM with the handler above. On Vercel, functions freeze between requests, so per the package docs @vercel/otel flushes after each request instead.
If you run several services, an OpenTelemetry Collector keeps keys, sampling and retries in one place and out of each app.
Common problems
This section maps each symptom to its cause, in the order you are likely to hit them.
instrumentation.ts is not running
Put a console.log at the top of register(). If it never prints at server start, check these in order:
- Location. Project root, or
src/when the project has one. Not insideapporpages, and in a monorepo, the Next.js app's own directory. Next.js 16.4 still loaded a root-level file in a test withsrc/app, but the docs requiresrc/instrumentation.tsthere, so follow them. - Name and export.
instrumentation.tsor.js(or yourpageExtensions), exporting a function named exactlyregister. - Version. Next.js 13.4 and 14 ignore the file without
experimental.instrumentationHook.
Module not found: Can't resolve 'stream', 'fs' or 'net'
A webpack build that fails like this has pulled the Node SDK into the Edge bundle:
./node_modules/@grpc/grpc-js/build/src/call.js:22:1
Module not found: Can't resolve 'stream'
Import trace for requested module:
./node_modules/@opentelemetry/sdk-node/dist/index.mjs
./instrumentation.node.ts
./instrumentation.ts - The clue is the import trace ending at
instrumentation.ts. - gRPC is not the cause.
sdk-nodeincludes the gRPC exporters whether you use them or not, and they are the first Node-only import the Edge compiler meets. - The fix is the guarded dynamic import from the Node SDK setup. With it, the HTTP and gRPC exporters both built and ran under Turbopack and
next build --webpack, with noserverExternalPackagesentry.
Turbopack, the default bundler in Next.js 16, does not fail the build for the same mistake. Every request to an Edge route returns 500 at runtime instead:
Error: Failed to load external module node:module: TypeError: Native module not found: node:module ERESOLVE and mixed @opentelemetry versions
npm error ERESOLVE could not resolve
npm error Conflicting peer dependency: @opentelemetry/api@1.9.1
npm error peer @opentelemetry/api@">=1.0.0 <1.10.0" from @opentelemetry/sdk-trace-node@2.12.1
The OpenTelemetry JavaScript packages release in lines that must match. In the releases tested here, a 0.301 exporter goes with 3.x SDK packages and @opentelemetry/api 1.10, while 2.x SDK packages cap the API below 1.10.
- Install
sdk-nodeand the exporters at the same version and let them bring their own SDK packages. - Do not add
sdk-trace-nodeorsdk-trace-baseby hand. - Avoid
--legacy-peer-deps. It tends to leave two copies of the API, and spans silently go nowhere.
The app runs but no spans arrive
- No endpoint.
OTEL_EXPORTER_OTLP_ENDPOINTmust be set in the server's environment at runtime. A value in.env.localdoes not reach a Docker image or a hosted deployment. - Wrong path or protocol. The variable is a base URL and the exporter appends
/v1/traces. A URL passed in code is used as written. The OTLP guide lists what each status code means. - Too early to tell. The batch processor waits up to 5 seconds.
- Edge routes with the manual setup. The guard skips them by design.
- Sampled out. A leftover
OTEL_TRACES_SAMPLERin the environment applies to both setups.
Spans in dev but not after build, or the reverse
In the test, next dev exported the same span names as next start. When the two differ, look at these:
- Environment files.
next devloads.env.developmentand.env.local. A production server loads.env.productionor whatever the host injects. - Static pages. Prerendered pages are rendered once at build time and served from cache, so they produce no render span per request.
The downstream service starts a new trace
The request left without traceparent. Add the host to propagateContextUrls for @vercel/otel, or add the undici instrumentation for the Node SDK. See fetch spans and propagation.
No database spans
The driver was bundled, so it was never patched. Add it to serverExternalPackages as in the database section.
Send it to Maple
Maple is an OpenTelemetry-native backend, so either setup above works unchanged. Point the exporter at the ingest endpoint with your ingest key, deploy, and requests show up grouped by route:
.env
OTEL_SERVICE_NAME="storefront"
OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.maple.dev"
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_INGEST_KEY"
OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
The Next.js instrumentation doc adds logs and metrics to this setup, and the frontend tracing doc for Next.js covers the browser side.