Frameworks 13 min read

OpenTelemetry in Next.js

How to trace a Next.js app (App Router or Pages Router) with instrumentation.ts: which SDK to register, what spans Next.js gives you for free, and how to fix a setup that sends nothing. Tested with Next.js 16.4, @vercel/otel 2.3 and @opentelemetry/sdk-node 0.301 (November 2026).

David Granzin By David Granzin

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.ts goes in the project root, or in src/ if you use one. Next.js calls its register() once per server start.
  • @vercel/otel is the short path and runs in both runtimes. @opentelemetry/sdk-node is Node.js only and must sit behind a NEXT_RUNTIME === "nodejs" check.
  • Neither setup sends traceparent on outgoing fetch calls to your own APIs until you configure it.
  • Server Actions have no span of their own. They run inside the page's POST request 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 named register. Next.js runs it once per server start, before any request.
  • The location. Project root, next to next.config.ts, or src/ if your app or pages directory lives there. Never inside app.
  • Dev mode. register() also runs in next 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_RUNTIME at build time and drops the dead branch. That keeps the SDK out of the Edge bundle. A top-level import "./instrumentation.node" defeats it.
  • Use resourceFromAttributes. Older tutorials use new 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
RuntimesNode.js and EdgeNode.js only
Runtime guard neededNoYes
Outgoing fetchBuilt-in fetch instrumentation@opentelemetry/instrumentation-undici
traceparent sent by defaultOnly to Vercel deployment URLsTo every host, once undici instrumentation is on
Library instrumentationsAccepts them through instrumentationsFull set
Resource detectionVercel and runtime attributesHost, 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/otel works. In a test with one Edge route handler it exported that route's spans as a separate batch with process.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.route use /products/[slug], so every product page lands in one group. The concrete path is in http.target.
  • Older HTTP attribute names. Next.js emits http.method and http.status_code, not http.request.method and http.response.status_code.

Span names for App Router, Route Handlers and Server Actions

What ranSpan namenext.span_type
Any matched requestGET /products/[slug]BaseServer.handleRequest
Server Components renderrender route (app) /products/[slug]AppRender.getBodyResult
generateMetadatagenerateMetadata /products/[slug]/pageResolveMetadata.generateMetadata
Route handlerexecuting api route (app) /api/orders/[id]AppRouteRouteHandlers.runHandler
Server ActionPOST /products/[slug] (the page's request span)BaseServer.handleRequest
Middleware or proxymiddleware GETMiddleware.execute
Server-side fetchfetch GET https://api.example.com/stockAppRender.fetch
Pages Router datagetServerSideProps /route, getStaticProps /routeRender.getServerSideProps, Render.getStaticProps
Pages Router API routeexecuting api route (pages) /api/routeNode.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 its fetch, database or custom spans.
  • Server Actions are a POST to the page. An action called from /products/[slug] appears as POST /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.ts or middleware.ts, the trace root is a server span named only GET, as in the tree above. Group by http.route, not by root span name. Requests that match no route (404s) are also named just GET.

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 sets NEXT_OTEL_FETCH_DISABLED=1 for you. It injects traceparent only for Vercel deployment URLs. In the test, a call to another host arrived with no header until the host was added to propagateContextUrls.
  • The Node SDK needs @opentelemetry/instrumentation-undici, because Node's fetch is built on undici. It hooks in through diagnostics_channel, so it works on bundled server code, and it injects traceparent on 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, express and pino.

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_id is the custom span's, not the request's, so the line points at the exact step.
  • A mixin is a plain function call, so it works whether or not Next.js bundles the logger. The same lines work in a console.log wrapper.
  • Logs stay on stdout, where most log pipelines collect them. To ship them over OTLP instead, both registerOTel and NodeSDK accept logRecordProcessors.

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.version and deployment.environment.name at minimum. Values set in code win over OTEL_RESOURCE_ATTRIBUTES.
  • Sampling. The default keeps every trace, at around ten spans per request before your own. parentbased_traceidratio keeps 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 start server 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 SIGTERM by default. In a test, a request followed by SIGTERM lost 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=true in 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/otel on your own servers, registerOTel returns no handle to flush, so a shorter OTEL_BSP_SCHEDULE_DELAY is the way to shrink the window. On Vercel the package flushes after each request through waitUntil.

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 inside app or pages, and in a monorepo, the Next.js app's own directory. Next.js 16.4 still loaded a root-level file in a test with src/app, but the docs require src/instrumentation.ts there, so follow them.
  • Name and export. instrumentation.ts or .js (or your pageExtensions), exporting a function named exactly register.
  • 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-node includes 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 no serverExternalPackages entry.

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-node and the exporters at the same version and let them bring their own SDK packages.
  • Do not add sdk-trace-node or sdk-trace-base by 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_ENDPOINT must be set in the server's environment at runtime. A value in .env.local does 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_SAMPLER in 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 dev loads .env.development and .env.local. A production server loads .env.production or 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"
A trace in Maple's timeline view: a POST /api/checkout request shown as a waterfall of 15 spans across 6 services, with the failing span marked as an error.
A trace waterfall in Maple. Next.js server, render and fetch spans appear in the same view, next to the services they call.

The Next.js instrumentation doc adds logs and metrics to this setup, and the frontend tracing doc for Next.js covers the browser side.

Sources and further reading

FAQ

Common questions

Does Next.js support OpenTelemetry?
Yes. Next.js creates OpenTelemetry spans for requests, rendering, route handlers, middleware and fetch calls on its own. It ships no exporter, so you register an SDK in instrumentation.ts, with @vercel/otel or @opentelemetry/sdk-node, to send those spans somewhere.
Where does instrumentation.ts go in a Next.js project?
In the project root, next to next.config.ts and package.json. If the project uses a src directory, put it at src/instrumentation.ts beside app or pages. It does not go inside app or pages. Next.js calls its exported register function once when the server starts.
Should I use @vercel/otel or @opentelemetry/sdk-node?
Use @vercel/otel when you want the shortest setup or you run code in the Edge runtime. It works on any host, not only Vercel. Use @opentelemetry/sdk-node when you run on Node.js only and want library instrumentations for databases, queues or other clients with full control over the pipeline.
Why do I need the NEXT_RUNTIME check in instrumentation.ts?
Next.js compiles instrumentation.ts for every runtime the app uses. @opentelemetry/sdk-node imports Node.js modules such as stream and fs, which do not exist in the Edge runtime. Importing it inside an if (process.env.NEXT_RUNTIME === 'nodejs') block keeps it out of the Edge bundle.
Does OpenTelemetry work in next dev?
Yes. register runs in next dev as well as next start, and spans are exported from both. Dev mode adds compile time to span durations and the resource reports a development environment, so measure performance against a production build.
How do I trace Server Actions in Next.js?
A Server Action has no span of its own. It runs inside the POST request span of the page that called it, named like POST /products/[slug]. Add attributes to that span with trace.getActiveSpan(), or wrap the action body in tracer.startActiveSpan to get a named child span.

See your first trace today.

Add the SDK, point your OTLP exporter at Maple, and traces arrive.

maple.dev: observability on OpenTelemetry