Why Observability Matters in Next.js Applications
Next.js 15 applications mix React Server Components, Route Handlers, Server Actions, Middleware, and Edge Runtime functions. A single user request can trigger multiple fetch calls, Drizzle ORM transactions, background BullMQ jobs, and streaming responses from the Vercel AI SDK. When a customer reports a stuck checkout or slow AI response, scattered console logs and error trackers rarely show the exact sequence, timing, and causal relationships across these boundaries.
OpenTelemetry solves this by assigning a single trace ID that follows the request from the initial browser fetch through middleware, server components, database queries, external API calls, and even LLM inference steps. Every span records start time, end time, attributes, events, and status. This unified data set lets engineers query for all traces where a specific tenant ID experienced a database timeout in the last hour.
Without standardized tracing, teams waste hours correlating request IDs across application logs, PostgreSQL slow query logs, and S3 access logs. OpenTelemetry replaces this manual stitching with a single searchable timeline. It also records metrics such as request duration histograms and error counts that feed directly into alerting systems. The specification is vendor neutral, so the same instrumentation works when moving from Vercel to a self-hosted Kubernetes cluster running on AWS or Hetzner.
Next.js 15 specific features such as Partial Prerendering and React Cache create additional layers that are opaque to traditional log-based debugging. Tracing reveals exactly when a cached segment is served versus when a dynamic segment triggers a fresh database roundtrip. This visibility drives targeted optimization efforts instead of broad guesses.
OpenTelemetry Architecture Overview
OpenTelemetry defines three signals: traces, metrics, and logs. Traces represent causality between operations as a tree of spans. Metrics provide aggregated quantitative data such as latency histograms and counters. Logs can be correlated to traces via trace and span identifiers. The API package provides the interfaces while the SDK supplies the concrete implementations for sampling, batching, and exporting.
In a typical Next.js setup the application emits OTLP over HTTP to a collector. The collector applies processors that can filter attributes, add Kubernetes pod metadata, or route different signals to different backends. Jaeger receives traces, Prometheus scrapes metrics, and Grafana visualizes both. This separation means application code never contains Jaeger or Prometheus specific logic.
Current stable versions used in this guide are @opentelemetry/api at 1.9.0, @opentelemetry/sdk-trace-node at 1.26.0, @opentelemetry/exporter-trace-otlp-http at 0.53.0, and @opentelemetry/auto-instrumentations-node at 0.47.0. These versions support the v1.0 stable trace semantic conventions and work with Node.js 20 and 22, the runtimes targeted by Next.js 15.
The resource object attaches immutable attributes such as service name and deployment environment to every span and metric. Semantic conventions define standard attribute keys like http.request.method, db.query.text, and gen_ai.request.model so that backends render meaningful names and icons automatically.
Project Setup and Package Installation
Initialize the project with npx create-next-app@15.0.1 otel-demo --typescript --tailwind --eslint --app --yes. Then install the instrumentation packages with exact versions to ensure reproducibility:
npm install @opentelemetry/api@1.9.0 \
@opentelemetry/sdk-trace-node@1.26.0 \
@opentelemetry/exporter-trace-otlp-http@0.53.0 \
@opentelemetry/auto-instrumentations-node@0.47.0 \
@opentelemetry/instrumentation-http@0.53.0 \
@opentelemetry/instrumentation-pg@0.47.0 \
@opentelemetry/instrumentation-drizzle@0.1.0 \
@opentelemetry/resources@1.26.0 \
@opentelemetry/semantic-conventions@1.26.0
Add development dependencies for local collector testing: npm install --save-dev @opentelemetry/sdk-metrics. Update tsconfig.json to include "experimentalDecorators": true if you plan to use decorator-based instrumentation in shared libraries. Create an .env.local file with the following keys:
OTEL_SERVICE_NAME=nextjs-15-demo
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:4318/v1/traces
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://localhost:4318/v1/metrics
NODE_ENV=development
DATABASE_URL=postgres://user:pass@localhost:5432/demo
These environment variables are read by both the SDK and the collector. The instrumentation file must be compiled or loaded via ts-node during local development using NODE_OPTIONS='--loader ts-node/esm'.
Configuring the OpenTelemetry SDK
Create instrumentation.ts at the project root. Next.js automatically invokes the register() export when the file is present. The code below configures tracing, adds automatic instrumentation, and registers a graceful shutdown hook:
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { MeterProvider } from '@opentelemetry/sdk-metrics';
const traceExporter = new OTLPTraceExporter({
url: process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,
headers: { 'Content-Type': 'application/json' },
});
const metricExporter = new OTLPMetricExporter({
url: process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT,
});
const resource = new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || 'nextjs-app',
[SemanticResourceAttributes.SERVICE_VERSION]: '1.2.3',
[SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT]: process.env.NODE_ENV,
});
const sdk = new NodeSDK({
resource,
traceExporter,
instrumentations: [getNodeAutoInstrumentations({
'@opentelemetry/instrumentation-http': {
ignoreIncomingPaths: ['/healthz', '/favicon.ico', '/_next/static'],
ignoreOutgoingUrls: [/.*\.sentry\.io/],
},
'@opentelemetry/instrumentation-pg': { suppressInternalInstrumentation: true },
'@opentelemetry/instrumentation-drizzle': { enabled: true },
})],
});
const meterProvider = new MeterProvider({ resource });
meterProvider.addMetricReader({ exporter: metricExporter });
sdk.start();
meterProvider.start();
process.on('SIGTERM', async () => {
await sdk.shutdown();
await meterProvider.shutdown();
console.log('OpenTelemetry SDK shut down gracefully');
});
The ignoreIncomingPaths array prevents noise from static assets and health checks. The suppressInternalInstrumentation flag avoids recursive spans when the instrumentation itself makes database calls for sampling decisions. Each configuration option directly affects data volume and performance overhead.
Auto-Instrumentation for Database Queries
With Drizzle ORM and the pg driver, auto-instrumentation captures every executed statement. Initialize the client once and all queries inherit the active trace context:
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export const db = drizzle(pool);
// Example query that will be traced automatically
export async function getTenantInvoices(tenantId: string) {
return db.query.invoices.findMany({
where: (invoices, { eq }) => eq(invoices.tenantId, tenantId),
limit: 50,
});
}
In Jaeger the resulting span shows db.system set to postgresql, db.operation as SELECT, the full query text (truncated for high-cardinality safety), and the exact duration. If the query exceeds 250ms you can configure the instrumentation to attach an event with the stack trace at the time the query started. This level of detail reveals missing indexes or sequential scans that only appear under production load with realistic data volumes.
Trade-off: capturing the full query text increases collector payload size. For compliance-sensitive environments, set db.statement to a parameterized form or disable query text capture entirely for tables containing personal data.
Manual Instrumentation for Business Logic
Auto-instrumentation stops at library boundaries. Create a dedicated tracer for domain operations and wrap critical functions. The following example instruments a complete invoice generation flow with nested spans and baggage for tenant isolation:
import { trace, context, propagation, SpanStatusCode } from '@opentelemetry/api';
const tracer = trace.getTracer('billing', '2.1.0');
export async function generateInvoice(tenantId: string, orderId: string) {
const baggage = propagation.createBaggage({
'tenant.id': { value: tenantId },
});
const ctx = propagation.setBaggage(context.active(), baggage);
return context.with(ctx, () => tracer.startActiveSpan('invoice.generate', async (span) => {
span.setAttribute('tenant.id', tenantId);
span.setAttribute('order.id', orderId);
try {
const itemsSpan = tracer.startSpan('invoice.fetch_items');
const items = await db.query.orderItems.findMany({ where: { orderId } });
itemsSpan.end();
const pdfSpan = tracer.startSpan('invoice.render_pdf');
const pdfBuffer = await renderPdfTemplate(items);
pdfSpan.setAttribute('pdf.size_bytes', pdfBuffer.length);
pdfSpan.end();
const uploadSpan = tracer.startSpan('invoice.upload_s3');
const s3Key = await uploadToS3(pdfBuffer, `invoices/${tenantId}/${orderId}.pdf`);
uploadSpan.setAttribute('s3.key', s3Key);
uploadSpan.end();
span.setStatus({ code: SpanStatusCode.OK });
return s3Key;
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR, message: (err as Error).message });
span.recordException(err as Error);
throw err;
} finally {
span.end();
}
}));
}
Baggage propagates the tenant identifier to every child service automatically. In a microservices architecture the receiving service can read the baggage and attach the same tenant ID to its own spans without additional parameters. This pattern scales to complex workflows involving multiple worker queues and external webhooks.
Context Propagation Across Server Actions and Middleware
Server Actions in Next.js 15 are invoked via POST requests that carry the trace context in headers. The HTTP instrumentation extracts the traceparent header automatically. To ensure Server Actions started from client components inherit the correct parent span, wrap the action handler:
'use server';
import { trace } from '@opentelemetry/api';
const tracer = trace.getTracer('server-actions');
export async function createInvoiceAction(formData: FormData) {
return tracer.startActiveSpan('action.createInvoice', async (span) => {
const tenantId = formData.get('tenantId') as string;
span.setAttribute('tenant.id', tenantId);
const result = await generateInvoice(tenantId, formData.get('orderId') as string);
span.end();
return result;
});
}
Middleware can enrich the root span before any application code runs. Reading custom headers and setting attributes early ensures the entire trace carries user or session context. For Edge Runtime, use the lightweight @opentelemetry/api only, because the full Node SDK is not compatible with the edge runtime.
Setting Up the OpenTelemetry Collector
The collector decouples the application from backend changes. The expanded docker-compose.yml includes persistent volumes and the full collector configuration:
version: '3.8'
services:
collector:
image: otel/opentelemetry-collector-contrib:0.104.0
command: [--config=/etc/otel-collector-config.yaml]
volumes:
- ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
ports:
- "4317:4317"
- "4318:4318"
depends_on:
- jaeger
- prometheus
jaeger:
image: jaegertracing/all-in-one:1.57
ports: ["16686:16686"]
prometheus:
image: prom/prometheus:v2.52.0
ports: ["9090:9090"]
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
grafana:
image: grafana/grafana:10.4.2
ports: ["3000:3000"]
The collector config uses the batch processor with a 5-second timeout and 512 span limit, reducing network overhead. Tail-based sampling rules keep all traces containing errors or spans longer than 2 seconds while sampling the remainder at 10 percent. These settings balance completeness and cost.
Building Grafana Dashboards for Next.js Workloads
In Grafana import the Jaeger datasource and Prometheus datasource. Create a dashboard with these panels: latency heatmap for http.server.request.duration filtered by service.name = 'nextjs-15-demo', error rate calculated as sum(rate(http.server.duration_count{status_code=~'5..'})) / sum(rate(http.server.duration_count)), top 10 slowest database queries using span attributes, and a trace list panel showing recent traces containing the attribute tenant.id.
Use Grafana's trace view to jump from a high-latency HTTP span directly into the nested PDF rendering span. Set an alert that triggers when the 95th percentile of checkout route latency exceeds 1800ms for more than 3 minutes. These dashboards become the single source of truth during on-call incidents.
Sampling Strategies for Production
Configure a parent-based sampler that respects upstream sampling decisions and applies a ratio sampler only to root spans. For routes starting with /api/billing sample at a higher rate because these paths affect revenue. The collector's tail-based sampler further refines the data by keeping traces that contain any span with duration greater than 800ms or status code ERROR.
Adjust the ratio based on observed traffic volume. Services under a few hundred requests per second can safely sample at 25 percent while still keeping Jaeger responsive. Higher traffic services reduce to 1-5 percent and rely on tail sampling to capture outliers. Always test sampling rules with synthetic traffic before rolling out to production.
Tracing LLM Calls with Vercel AI SDK
The Vercel AI SDK streamText function can be wrapped to record model name, token counts, and tool usage as span attributes. This creates a clear timeline between the user request, prompt construction, model inference, and streamed response:
import { streamText } from 'ai';
import { trace } from '@opentelemetry/api';
const llmTracer = trace.getTracer('llm');
export async function generateSummary(prompt: string) {
return llmTracer.startActiveSpan('llm.summary', async (span) => {
span.setAttribute('llm.model', 'llama3.1-70b');
span.setAttribute('llm.prompt_tokens', prompt.split(' ').length);
const result = await streamText({
model: groq('llama-3.1-70b-versatile'),
prompt,
onFinish: (data) => {
span.setAttribute('llm.completion_tokens', data.usage.completionTokens);
span.setAttribute('llm.total_tokens', data.usage.totalTokens);
},
});
span.end();
return result;
});
}
In Grafana these spans appear linked to the parent HTTP request. When an LLM call exceeds its timeout the trace clearly shows whether the delay occurred inside token generation or network transfer to the Groq API.
Integrating Metrics Collection
Beyond traces, the SDK can emit runtime metrics and custom counters. Register a counter for invoice generations per tenant and a histogram for PDF render duration. These metrics are scraped by Prometheus every 15 seconds and used for capacity planning. The MeterProvider initialized earlier makes these available without additional HTTP calls from the application.
Correlating Logs with Traces
Use pino with the OpenTelemetry context injector. Every log line automatically receives trace_id and span_id fields. In Grafana Loki or Jaeger you can jump from a log line directly into the full trace. This eliminates the need for custom request ID propagation code that often drifts out of sync.
Testing and Validation
Run the full stack locally with docker compose up -d. Start the Next.js server with NODE_OPTIONS='--require ./instrumentation.js' npm run dev. Execute a test request with curl -H "Content-Type: application/json" http://localhost:3000/api/invoice -d '{"tenantId":"abc123"}'. Open Jaeger at http://localhost:16686 and search for nextjs-15-demo. The trace should display at least seven spans including the manual business logic spans and the automatic PostgreSQL span.
Validate context propagation by checking that the tenant ID appears on every child span. Use the Jaeger dependency graph to confirm that the service map shows correct call relationships between Next.js and the PostgreSQL backend.
Production Deployment Considerations
The production Dockerfile uses a multi-stage build to minimize size. The final stage copies only the compiled instrumentation.js, next.config.js, and the .next directory. Set resource requests of 512Mi memory and 250m CPU per pod to accommodate the extra overhead of batching and exporting. In Kubernetes the OpenTelemetry Operator can inject the agent automatically, removing the need to modify every deployment manifest.
Monitor the SDK itself by exporting its internal metrics. Track export queue length and dropped spans to detect collector backpressure before it affects application latency.
Common Pitfalls and How to Avoid Them
1. Initializing the SDK after Next.js has started the HTTP server. Solution: always use the register() function or load via NODE_OPTIONS before next start.
2. High-cardinality attributes such as full URLs or email addresses. Solution: use low-cardinality keys like user.id and sanitize query parameters.
3. Losing context inside Promise.all. Solution: wrap each promise with context.with or use startActiveSpan inside the mapped function.
4. Collector overload from unfiltered health checks. Solution: explicitly ignore those paths in the HTTP instrumentation configuration.
5. Forgetting to call span.end() in error paths. Solution: always use try/finally blocks as shown in the examples.
6. Incompatible versions between API and SDK. Solution: keep all OpenTelemetry packages at the same minor version.
7. Running full tracing on Edge Runtime functions. Solution: use only the API package and forward trace headers manually.
End-to-End Example: Tracing a Multi-Tenant Invoice Generation Flow
The complete route handler combines middleware context, manual spans, database queries, PDF rendering, and S3 upload. The resulting trace in Jaeger shows a root span of 1240ms containing a 340ms database span, a 620ms PDF generation span, and a 180ms S3 upload span. Attributes on the root span include tenant ID, order ID, and final S3 URL. Errors in any child span bubble up with full stack traces attached. This single view replaces hours of log searching across three different systems and gives precise data for optimizing the slowest segment of the flow.
By following the patterns in this guide, teams gain production-grade observability that scales with the application. The initial setup cost is repaid many times over through faster incident resolution and data-driven performance improvements.
