OpenTelemetry guide
OpenTelemetry for Next.js
Next.js calls a register() function from instrumentation.ts when the server starts. That is where OpenTelemetry goes, and Next.js adds its own spans for routes and rendering.
3 min read10 sectionsUpdated
On this page
// instrumentation.ts (project root or src/)
export async function register() {
if (process.env.NEXT_RUNTIME !== 'nodejs') return; // the Edge runtime is not instrumented
const { NodeSDK } = await import('@opentelemetry/sdk-node');
const { OTLPTraceExporter } = await import('@opentelemetry/exporter-trace-otlp-http');
const { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler } = await import('@opentelemetry/sdk-trace-base');
const { resourceFromAttributes } = await import('@opentelemetry/resources');
const { UndiciInstrumentation } = await import('@opentelemetry/instrumentation-undici');
const exporter = new OTLPTraceExporter({
url: `${process.env.VITALRIX_URL}/api/v1/traces/otlp/v1/traces`,
headers: { 'x-api-key': process.env.VITALRIX_API_KEY ?? '' },
});
new NodeSDK({
resource: resourceFromAttributes({
'service.name': process.env.OTEL_SERVICE_NAME ?? 'web',
'service.version': process.env.SERVICE_VERSION ?? '0.0.0',
'deployment.environment.name': process.env.DEPLOYMENT_ENVIRONMENT ?? 'production',
}),
sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(Number(process.env.TRACE_SAMPLE_RATE ?? 1)) }),
spanProcessors: [new BatchSpanProcessor(exporter, { maxQueueSize: 2048, maxExportBatchSize: 512 })],
instrumentations: [new UndiciInstrumentation()],
}).start();
}VITALRIX_URL=https://api.vitalrix.com
VITALRIX_API_KEY=your_trace_ingestion_key # server-side only; never NEXT_PUBLIC_
OTEL_SERVICE_NAME=storefront-web
SERVICE_VERSION=$(git rev-parse --short HEAD)
DEPLOYMENT_ENVIRONMENT=productionWhat you get
Next.js emits its own spans for incoming requests, route handlers and server rendering, named by route. The undici instrumentation adds a span for each server-side fetch, with the traceparent header so downstream services join the trace. Database clients you call from server components or route handlers need their own instrumentation packages (for example for pg or Prisma).
Keep the key on the server
The API key must never reach the browser. Do not prefix it with NEXT_PUBLIC_, and only read it inside instrumentation.ts, which runs on the server. For browser-side performance (Core Web Vitals, JavaScript errors), use real user monitoring with its public site key instead.
Check that it works
- Send a few requests to the app.
- In VitalRix, open APM: storefront-web appears in the service catalog within a minute, with request rate, error rate and p95.
- Open an endpoint and then one request to see its trace waterfall, including database spans.
- If nothing arrives, check the exporter's (or the Collector's) logs for export errors: 401 means the key or header is wrong, 402 that a new host is over the plan's APM host allowance. The packages have a
checkcommand that sends one test log.
Add service.version so new releases appear as deploy markers, and put the trace ID in your logs so each trace shows its log lines. See APM and logs, metrics and traces.
Do I need the experimental instrumentationHook flag?
Recent Next.js versions load instrumentation.ts without it. Older versions required experimental.instrumentationHook in next.config.
Can I use @vercel/otel instead?
Yes. It wraps the same SDK with Next.js defaults. Point its exporter at the same URL and header.
Related reading
- How to monitor a Next.js app: How to monitor a Next.js app in production: uptime checks, Core Web Vitals, server and edge errors, OpenTelemetry traces for SSR and API routes, and alerts.
- OpenTelemetry for FastAPI: Trace a FastAPI service with OpenTelemetry: instrument the app, async database drivers and httpx, run uvicorn workers correctly and export.
- OpenTelemetry for Go: Instrument a Go service with OpenTelemetry: set up the tracer provider, wrap net/http with otelhttp, pass context everywhere and export the spans.
- OpenTelemetry for PHP and Laravel: Trace a Laravel app with OpenTelemetry: install the PHP extension and auto-instrumentation packages, configure PHP-FPM and trace queries.
- OpenTelemetry for Flask: Instrument a Flask app with OpenTelemetry, in code or with zero code: trace routes, SQLAlchemy and outgoing calls, and export to VitalRix.
- OpenTelemetry for Python: setup guide: Add OpenTelemetry to a Python service: install the distro, auto-instrument with opentelemetry-instrument, export to VitalRix and add custom spans.
Watch your own site and services with VitalRix
Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.