Observability · Nov 17, 2026 · 11 min read

OpenTelemetry in Next.js: Tracing, Metrics & Context Propagation

Hands-on guide to instrumenting Next.js applications with OpenTelemetry JS SDK, Jaeger tracing, Prometheus metrics, database instrumentation, and practical patterns for API routes, server actions, and

OpenTelemetry in Next.js: Tracing, Metrics & Context Propagation

Why Distributed Tracing Matters in Next.js Applications

Next.js applications combine server components, route handlers, middleware, server actions, and frequent calls to databases, caches, and third-party APIs. When a request fails or latency spikes, identifying whether the issue originated in a Drizzle query, an OpenAI completion, Redis operation, or edge middleware requires visibility beyond console logs.

OpenTelemetry provides a vendor-neutral way to capture traces, metrics, and logs with automatic and manual instrumentation. The JavaScript ecosystem has reached production readiness with stable APIs that integrate cleanly with the App Router and React Server Components execution model.

OpenTelemetry Core Concepts

OpenTelemetry defines three signals: traces, metrics, and logs. A trace represents a single request as a tree of spans. Each span records start time, duration, attributes, events, and status. Metrics include counters, gauges, and histograms. Logs can be correlated to traces via trace ID and span ID.

The architecture separates API, SDK, and exporters. The @opentelemetry/api package provides the interfaces used in application code. The SDK handles sampling, processing, and export. Exporters send data to Jaeger, Prometheus, or commercial backends.

Context propagation uses W3C Trace Context headers so traces continue across service boundaries, including fetch calls to other Next.js route handlers or external microservices.

Project Setup and Package Installation

Create a new Next.js 15 application or use an existing one. Install the following packages with exact versions known to work together:

npm install \
  @opentelemetry/api@1.9.0 \
  @opentelemetry/sdk-trace-node@1.25.0 \
  @opentelemetry/sdk-metrics@1.25.0 \
  @opentelemetry/exporter-trace-otlp-http@0.52.0 \
  @opentelemetry/exporter-metrics-otlp-http@0.52.0 \
  @opentelemetry/auto-instrumentations-node@0.47.0 \
  @opentelemetry/instrumentation-http@0.52.0 \
  @opentelemetry/instrumentation-pg@0.44.0 \
  @opentelemetry/instrumentation-redis-4@0.42.0 \
  @opentelemetry/instrumentation-undici@0.7.0

These versions are compatible as of late 2024. The auto-instrumentations package registers many common libraries automatically when configured.

Initializing the SDK in Next.js

Next.js runs in both server and edge runtimes. For full SDK features we target the Node.js runtime. Create a file instrumentation.ts in the project root:

import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';

const traceExporter = new OTLPTraceExporter({
  url: 'http://localhost:4318/v1/traces',
});

const metricReader = new PeriodicExportingMetricReader({
  exporter: new OTLPMetricExporter({
    url: 'http://localhost:4318/v1/metrics',
  }),
  exportIntervalMillis: 10000,
});

const sdk = new NodeSDK({
  traceExporter,
  metricReader,
  instrumentations: [getNodeAutoInstrumentations({
    '@opentelemetry/instrumentation-http': {
      ignoreIncomingPaths: ['/health', '/favicon.ico'],
    },
    '@opentelemetry/instrumentation-fs': {
      enabled: false,
    },
  })],
});

sdk.start();

// Graceful shutdown
process.on('SIGTERM', () => {
  sdk.shutdown()
    .then(() => console.log('OpenTelemetry SDK shut down'))
    .catch(console.error);
});

Register this file by setting instrumentationHook: true in next.config.js and importing it at the top of your server.js custom server or using the experimental instrumentation file supported in Next.js 15.

Configuring Jaeger for Local Development

Run Jaeger with Docker to visualize traces:

docker run -d \
  --name jaeger \
  -e COLLECTOR_OTLP_ENABLED=true \
  -p 16686:16686 \
  -p 4317:4317 \
  -p 4318:4318 \
  jaegertracing/all-in-one:1.57

Access the Jaeger UI at http://localhost:16686. All traces from your Next.js application will appear after the first request. The UI allows searching by service name (default is nextjs-app), operation name, or tags such as user.id.

Automatic Instrumentation Benefits and Limits

The HTTP instrumentation automatically creates spans for incoming requests and outgoing fetch calls. Database instrumentations add spans for queries with the exact SQL statement and execution time as attributes.

For a Drizzle ORM query, the @opentelemetry/instrumentation-pg will capture the underlying PostgreSQL call if you use the pg driver. Attributes include db.statement, db.operation, and db.name.

Limitations appear with edge runtime code and certain caching layers. Server Components that render at build time do not produce runtime traces. Focus instrumentation on dynamic routes, route handlers, and server actions.

Adding Custom Spans for Business Logic

Automatic spans are useful but insufficient for domain-specific operations. Use the API to create custom spans around critical sections.

import { trace, SpanStatusCode, context } from '@opentelemetry/api';

const tracer = trace.getTracer('nextjs-app', '1.0.0');

async function processOrder(orderData: Order) {
  return tracer.startActiveSpan('process-order', async (span) => {
    try {
      span.setAttribute('order.id', orderData.id);
      span.setAttribute('customer.id', orderData.customerId);
      
      // Check inventory
      const inventorySpan = tracer.startSpan('check-inventory');
      const stock = await checkStock(orderData.items);
      inventorySpan.setAttribute('items.checked', orderData.items.length);
      inventorySpan.end();
      
      if (stock < 1) {
        span.setStatus({ code: SpanStatusCode.ERROR, message: 'Out of stock' });
        throw new Error('Insufficient inventory');
      }
      
      const paymentSpan = tracer.startSpan('process-payment');
      const paymentResult = await chargeCard(orderData.payment);
      paymentSpan.setAttribute('payment.provider', 'stripe');
      paymentSpan.setAttribute('payment.amount', orderData.total);
      paymentSpan.end();
      
      span.setStatus({ code: SpanStatusCode.OK });
      return createOrderRecord(orderData);
    } catch (error) {
      span.recordException(error as Error);
      span.setStatus({ 
        code: SpanStatusCode.ERROR, 
        message: (error as Error).message 
      });
      throw error;
    } finally {
      span.end();
    }
  });
}

This pattern creates nested spans visible in Jaeger as a tree. Attributes enable filtering and grouping in observability tools.

Context Propagation Across Boundaries

OpenTelemetry automatically injects trace context into outgoing HTTP requests via traceparent and tracestate headers. When calling another service or a separate Next.js API route, the downstream service continues the same trace.

For server actions called from client components, context is maintained within the same process. When using React Server Components that call async functions, the active context is automatically available inside those functions.

To manually propagate context across async boundaries or worker threads, use context.bind or the async-hooks context manager included in the Node SDK.

Instrumenting LLM Calls

Applications using OpenAI, Anthropic, or local models benefit from dedicated spans that capture token usage and model parameters.

async function generateSummary(text: string) {
  return tracer.startActiveSpan('llm.generate-summary', async (span) => {
    span.setAttribute('llm.model', 'gpt-4o-mini');
    span.setAttribute('llm.provider', 'openai');
    span.setAttribute('llm.input_tokens', 1243); // updated after response
    
    const response = await openai.chat.completions.create({
      model: 'gpt-4o-mini',
      messages: [{ role: 'user', content: text }],
    });
    
    span.setAttribute('llm.output_tokens', response.usage?.completion_tokens || 0);
    span.setAttribute('llm.total_tokens', response.usage?.total_tokens || 0);
    
    if (response.choices[0].finish_reason === 'length') {
      span.setStatus({ 
        code: SpanStatusCode.ERROR, 
        message: 'Token limit reached' 
      });
    }
    
    return response.choices[0].message.content;
  });
}

These attributes allow cost tracking, performance analysis per model, and correlation between slow user requests and expensive LLM calls.

Recording Metrics with the Metrics SDK

Metrics complement traces by providing aggregate views. Create a meter and record counters or histograms:

import { metrics } from '@opentelemetry/api';

const meter = metrics.getMeter('nextjs-meter', '1.0.0');

const requestCounter = meter.createCounter('http.requests', {
  description: 'Total HTTP requests by route and status',
});

const latencyHistogram = meter.createHistogram('http.latency', {
  description: 'HTTP request latency in milliseconds',
  unit: 'ms',
});

// In a route handler or middleware
function recordRequest(method: string, route: string, status: number, duration: number) {
  requestCounter.add(1, {
    'http.method': method,
    'http.route': route,
    'http.status_code': status.toString(),
  });
  
  latencyHistogram.record(duration, {
    'http.route': route,
  });
}

The OTLPMetricExporter sends these to your collector or directly to Prometheus via the Prometheus exporter alternative.

Running Prometheus Locally

Use the Prometheus community OTLP receiver or the OpenTelemetry Prometheus exporter. For quick testing, run Prometheus that scrapes the OTLP HTTP endpoint or use the @opentelemetry/exporter-prometheus package which exposes a /metrics endpoint.

Example Prometheus configuration snippet:

scrape_configs:
  - job_name: 'nextjs-app'
    scrape_interval: 10s
    static_configs:
      - targets: ['localhost:9464']

Common metrics to track: request rate, error rate, latency percentiles (p95, p99), token usage per model, and database connection pool statistics.

Correlating Logs with Traces

Modern logging libraries can inject trace and span IDs into log records. For Pino, use the pino-opentelemetry transport or manually add context:

import pino from 'pino';
import { trace, context } from '@opentelemetry/api';

const logger = pino({
  level: 'info',
  timestamp: pino.stdTimeFunctions.isoTime,
});

function logWithTrace(level: string, message: string, attributes = {}) {
  const span = trace.getSpan(context.active());
  const logContext = span ? {
    trace_id: span.spanContext().traceId,
    span_id: span.spanContext().spanId,
    ...attributes
  } : attributes;
  
  logger[level](logContext, message);
}

This allows clicking from a log line in your observability platform directly into the corresponding trace.

Sampling Strategies for Production

Tracing every request creates significant overhead and storage costs. Use the TraceIdRatioBasedSampler for development (ratio 1.0) and ParentBasedSampler combined with a lower ratio in production.

Example configuration for 10% sampling while always sampling error traces:

import { SamplingDecision, ParentBasedSampler, TraceIdRatioBasedSampler } from '@opentelemetry/sdk-trace-base';

const sampler = new ParentBasedSampler({
  root: new TraceIdRatioBasedSampler(0.1),
});

Adjust the ratio based on traffic volume. High-traffic SaaS applications often use 1% or lower for head-based sampling and supplement with tail-based sampling in the collector for error or slow traces.

Database Instrumentation Details

When using PostgreSQL with the pg library or Drizzle, the instrumentation captures each query as a child span. To reduce noise from health checks or frequent small queries, configure instrumentation to ignore specific statements using regex filters.

For Redis, the instrumentation records commands like GET, SET, HGETALL with key names (consider sanitizing PII keys). Duration histograms help identify cache misses that cascade into database load.

Common Pitfalls and Solutions

  • Memory leaks from unended spans: Always call span.end() in a finally block. The active span API helps avoid this.
  • High cardinality attributes: Avoid adding unbounded values like full URLs with query parameters or user emails as attributes. Use stable identifiers such as tenant IDs or route patterns instead.
  • Span explosion in loops: Do not create a span for every item in a 5000-item batch. Create a single span with summary attributes or use events on a parent span.
  • Edge runtime incompatibility: The full Node SDK does not work in edge. Use lightweight @opentelemetry/api only and forward telemetry via fetch to a collector service.
  • Duplicate traces in Vercel: When deploying to Vercel, disable the built-in tracing or configure OpenTelemetry to export directly to your backend to avoid duplication.

End-to-End Example: Checkout Flow

Consider a checkout API route that validates cart, reserves inventory, processes payment, and sends confirmation. The complete trace contains spans for:

  1. HTTP request (automatic)
  2. Validate cart (custom)
  3. Inventory check (database)
  4. Payment gateway call (HTTP to Stripe)
  5. Create order record (database)
  6. Send receipt email (custom span around Resend or Postmark call)
  7. LLM-powered personalized thank-you message generation (optional)

Each span carries the tenant.id and checkout.session.id attributes, allowing business analytics queries such as "average checkout duration per tenant" or "payment failure rate by country".

In Jaeger you see the full waterfall, latency contribution per service, and error propagation. In Prometheus you track checkout completion rate as a counter with success/failure labels.

Production Deployment Considerations

For self-hosted environments, deploy the OpenTelemetry Collector as a sidecar or central service. The collector can receive OTLP, apply tail-based sampling, batch, and export to Jaeger, Prometheus, and your logging backend simultaneously.

Resource detection automatically adds service.name, service.version, cloud.provider, and deployment.environment attributes. Set these via environment variables:

OTEL_SERVICE_NAME=checkout-service
OTEL_RESOURCE_ATTRIBUTES=deployment.environment=production,service.version=2.3.1

Monitor the telemetry pipeline itself. Track export failures, dropped spans, and collector CPU/memory usage. Start with generous sampling in staging, measure overhead (typically low single-digit percentage of CPU and memory), then tune before production rollout.

Advanced Patterns for Multi-Tenant SaaS

In multi-tenant applications, attach tenant.id to the root span in middleware after resolving the tenant from hostname or subdomain. All child spans inherit this attribute automatically.

Use span links when a background job processes work initiated by a user request. The link connects the original trace to the background trace without making one a child of the other.

For rate-limited third-party APIs, record the remaining quota as a metric gauge and the retry count as an attribute on the HTTP span. This data helps prioritize engineering effort on the most expensive or flaky integrations.

Visualizing and Alerting

Jaeger excels at trace exploration but lacks long-term storage and alerting. Export traces to Tempo or a commercial APM that supports OTLP. For metrics, Grafana connected to Prometheus provides dashboards showing latency heatmaps, error budgets, and per-route performance.

Typical alerts include:

  • p95 latency above 800ms for checkout route
  • Error rate above 2% on payment spans
  • LLM average token usage exceeding budget threshold

These alerts reference the exact span names and attributes defined in your instrumentation code, closing the loop between code and operations.

Maintenance and Evolution

Treat instrumentation as production code. Add unit tests that verify custom spans are created with expected attributes using the OpenTelemetry testing utilities. Refactor span names when routes change to maintain clean dashboards.

Stay current with the SDK releases. The OpenTelemetry JavaScript community releases minor updates approximately monthly. Test upgrades in staging because exporter formats and default samplers occasionally change.

As your application adopts more AI features, extend the instrumentation to capture prompt templates, guardrail results, and RAG retrieval counts. These domain-specific attributes turn generic observability into business observability.

The combination of automatic instrumentation for infrastructure, manual spans for business logic, correlated metrics, and consistent context propagation gives teams the visibility required to debug complex Next.js applications quickly and to make data-driven decisions about performance and cost optimization.

Keep reading

Related Articles