Next.js Performance Monitoring with OpenTelemetry: A Practical Production Guide

Most Next.js apps I audit have the same blind spot. The team knows the site is slow. They have a vague sense that the checkout route "feels heavy". But when I ask which span inside that request is eating 800ms, nobody can answer. The Vercel dashboard shows a p95 number and that is it.
That gap is exactly what Next.js OpenTelemetry monitoring closes. OpenTelemetry (OTel) gives you vendor-neutral traces, metrics, and logs from your server components, route handlers, middleware, and database calls, all in one request timeline. You decide where the data goes. You are not locked into one dashboard.
I have set this up on client apps running on Vercel, on AWS ECS, and on plain Docker boxes in Dhaka and Sydney. This guide is the setup I actually ship, the backend choices I weigh, and the production traps that cost me a full weekend the first time.
Why bother with OpenTelemetry in a Next.js app
Next.js has decent built-in instrumentation hooks now. So why add another layer?
Because a slow page in production is rarely one problem. It is a server component doing three sequential fetches, a Prisma query with a missing index, and a middleware rewrite that runs on every request. Built-in timing tells you the request was slow. Tracing tells you where.
A few concrete things OTel gave me on real projects:
- Found a route handler that was awaiting a
fetchwith no cache, hitting a third-party API four times per render. - Caught a Postgres query that looked fast in staging (small dataset) and took 1.2s in production.
- Proved that a "slow page" report was actually the client's mobile network, not the server, which saved a pointless refactor.
- Correlated a spike in 500s to a single dependency version bump within minutes instead of hours of log grepping.
That is the value. Not dashboards for their own sake. A timeline that answers "which line of code is the problem" without adding console.time and redeploying.
How Next.js and OpenTelemetry fit together
Next.js ships an instrumentation.ts hook that runs once when the server starts. That is where you register your OTel SDK. Once registered, Next.js automatically wraps server component renders and route handlers in spans, and any auto-instrumentation you add (HTTP, Postgres, Prisma, etc.) attaches child spans to those. The official Next.js OpenTelemetry guide documents the hook and the @vercel/otel integration.
The flow looks like this:
Browser request
-> Next.js server (instrumentation.ts boots OTel SDK)
-> span: GET /product/[slug]
-> span: render Server Component
-> span: fetch to CMS
-> span: pg.query SELECT ...
-> OTel exporter ships spans
-> Collector (optional but recommended)
-> Backend (Grafana Tempo, ClickStack, Dynatrace, etc.)
Two runtimes matter here. The Node.js runtime supports full auto-instrumentation and is where you want your instrumentation to live. The Edge runtime is far more limited, and I will get to that below because it trips up a lot of people.
Step 1: Install the packages
For a Next.js 14/15 App Router project, the minimal set:
npm install @vercel/otel @opentelemetry/api
If you want auto-instrumentation for libraries (Postgres, Prisma, HTTP, etc.), add the relevant instrumentation packages:
npm install @opentelemetry/sdk-node \
@opentelemetry/auto-instrumentations-node \
@opentelemetry/exporter-trace-otlp-http
@vercel/otel is the convenient wrapper. It sets up a sensible SDK for you and works on Vercel and self-hosted. If you need fine control (custom sampler, custom resource attributes, metrics pipeline), drop down to @opentelemetry/sdk-node directly. I use @vercel/otel for most client apps because it is less code to maintain.
Pin your versions. OTel packages move fast and a mismatched @opentelemetry/api version across dependencies is the number one cause of "it silently does nothing". If you are also tightening your build pipeline, my Next.js 16 Turbopack migration guide covers the production config changes that pair well with this setup.
Step 2: Create instrumentation.ts
Put this at the root of your project (or inside src/ if you use that layout):
// instrumentation.ts
import { registerOTel } from '@vercel/otel'
export function register() {
registerOTel({
serviceName: 'my-nextjs-app',
})
}
That is the whole happy path. Next.js calls register() once at server startup, before your app handles requests.
If you need a custom exporter or sampler, use the SDK directly:
// instrumentation.ts
import { NodeSDK } from '@opentelemetry/sdk-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
import { ParentBasedSampler, TraceIdRatioBasedSampler } from '@opentelemetry/sdk-trace-node'
const sdk = new NodeSDK({
serviceName: 'my-nextjs-app',
traceExporter: new OTLPTraceExporter({
url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
}),
sampler: new ParentBasedSampler({
root: new TraceIdRatioBasedSampler(0.1),
}),
instrumentations: [getNodeAutoInstrumentations()],
})
sdk.start()
Make sure instrumentation.ts is actually picked up. In Next.js 15 it runs by default. On older configs you may need experimental.instrumentationHook: true in next.config.js (this was required in Next.js 13.4-14; it became stable and default in Next.js 15). If you add the file and see zero spans, check this first.
Step 3: Point it at a backend
You need somewhere for the spans to land. This is where teams stall, because there are a dozen options and the marketing pages all sound identical. Here is how I actually think about it.
| Backend | Type | Setup effort | Cost model | Best for |
|---|---|---|---|---|
| Grafana + Tempo + Loki (self-hosted) | OSS | Medium | Infra only | Teams already on Grafana, full control |
| ClickStack (ClickHouse-based) | OSS | Medium | Infra only | High-volume traces, cost-sensitive teams |
| Jaeger | OSS | Low | Infra only | Local dev, small projects |
| Vercel Observability | Vendor | Very low | Per-seat / usage | Apps already on Vercel, quick start |
| Sentry | Vendor | Low | Usage-based | Teams wanting errors + traces together |
| Dynatrace / Datadog | Vendor APM | Medium | Expensive at scale | Enterprises with compliance needs |
For most of the client apps I build, the sweet spot is an OTel Collector in front of Grafana Tempo (or ClickStack on high-traffic apps). The collector gives you a single ingestion point, batching, retries, and the freedom to swap backends later without touching app code. The OpenTelemetry Collector docs cover the full receiver/processor/exporter model.
A minimal collector config:
# otel-collector-config.yaml
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
grpc:
endpoint: 0.0.0.0:4317
processors:
batch: {}
exporters:
otlphttp:
endpoint: http://tempo:4318
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [otlphttp]
Then set OTEL_EXPORTER_OTLP_ENDPOINT=http://your-collector:4318 in your app environment. Done.
If you are deploying in Bangladesh or another region with limited local cloud options, self-hosting the collector and Tempo on a modest VPS is genuinely affordable and keeps latency low for regional users. I have run this stack on a 4GB box for a mid-traffic app without issues. The tradeoff is you own the uptime. If you are already running your own infrastructure, the same VPS discipline applies as in my n8n-on-Docker self-hosting guide.
Step 4: Add useful span attributes
Default spans are fine. Custom attributes are where debugging gets fast. Tag spans with things you will actually filter on later: tenant ID, plan tier, feature flag state, user region.
import { trace, SpanStatusCode } from '@opentelemetry/api'
const tracer = trace.getTracer('my-nextjs-app')
export async function getOrder(orderId: string) {
return tracer.startActiveSpan('getOrder', async (span) => {
span.setAttribute('order.id', orderId)
try {
const order = await db.order.findUnique({ where: { id: orderId } })
span.setAttribute('order.found', Boolean(order))
return order
} catch (err) {
span.recordException(err as Error)
span.setStatus({ code: SpanStatusCode.ERROR })
throw err
} finally {
span.end()
}
})
}
Two rules I follow. Never put PII or secrets in span attributes (emails, tokens, card data). And keep attribute cardinality sane. A user.id attribute on every span will explode your storage bill on some backends. Use user.tier or tenant.id instead when you can. The OpenTelemetry semantic conventions list the standard attribute names worth reusing.
Step 5: Sampling strategy that does not lie to you
In production you will not keep every trace. The question is how to sample without hiding the problems you care about.
My default for most apps:
- Head sampling at 10 percent for normal traffic.
- Always keep errors and slow requests using a tail-based sampler in the collector, or a custom sampler in code.
- 100 percent in staging so you can debug freely.
Head sampling is cheap and simple but it makes decisions before the request finishes, so it cannot know a request will fail. Tail sampling in the collector waits for the full trace, then decides. That is the right tool when you want "keep every error and every request over 2 seconds". See the tail sampling processor docs for the policy syntax.
If you are not ready for tail sampling, at least do this: sample at 10 percent but log every error separately, and correlate via trace ID. That gets you 80 percent of the value with 20 percent of the complexity.
Production gotchas that will cost you a weekend
I have hit every one of these. Learn from my pain.
The Edge runtime does not support full instrumentation
If your middleware or route runs on the Edge runtime, OTel auto-instrumentation largely will not work there. The Node SDK needs Node APIs that Edge does not provide. Options: move the heavy logic to a Node runtime route, or accept coarser tracing on Edge and log manually. Do not spend hours debugging "missing spans" in middleware before checking the runtime. The same runtime constraints shape how you choose transports for AI tooling, which I cover in MCP transport: stdio vs Streamable HTTP.
The unhandled error trap
Next.js catches errors in some places and swallows them before your span sees them. If your monitoring shows a clean success rate while users report failures, you have an error trap. Add explicit span.recordException and span.setStatus({ code: SpanStatusCode.ERROR }) in your own try/catch blocks. Do not trust auto-instrumentation alone for error reporting. When the data crossing your API boundary is untrusted, TypeScript type guards for Next.js keep those failures from turning into silent runtime surprises.
Memory leaks in fetch instrumentation
There have been reported issues with @opentelemetry/instrumentation-fetch leaking memory under high concurrency in some versions. Watch your process RSS over a few days after enabling it. If it climbs steadily, disable that specific instrumentation and use manual spans around critical fetches instead.
Spans that never export
If the SDK starts but nothing arrives at the backend, the usual suspects are: wrong endpoint URL, missing OTEL_EXPORTER_OTLP_ENDPOINT, a firewall blocking egress, or a batch processor that never flushes because the process exits. In serverless, make sure you await the SDK shutdown in a graceful exit path (e.g. await sdk.shutdown()).
Version mismatches
@opentelemetry/api must be a single version across your whole dependency tree. Duplicate copies cause silent no-ops. Run npm ls @opentelemetry/api and fix duplicates before you debug anything else. This is the same class of problem as hallucinated or drifted dependencies, which I walk through in my AI hallucinated dependencies verification checklist.
A quick checklist before you ship
-
instrumentation.tsexists andregister()runs (add a log to confirm on boot). -
serviceNameis set and unique per environment. - Exporter endpoint is correct and reachable from the deploy target.
- Sampling is configured (10 percent default, errors always kept).
- No PII in span attributes.
- Edge runtime routes handled or documented.
- Memory watched for 48 hours after enabling fetch instrumentation.
- One dashboard exists with: p95 latency, error rate, slowest routes, slowest DB spans.
That last item matters more than the rest. A trace backend nobody looks at is just a bill.
Who should actually do this
If you are a solo dev on a small marketing site, this is overkill. Use Vercel's built-in observability and move on.
If you are running a real product with paying users, a database, and third-party APIs, Next.js OpenTelemetry monitoring is worth the afternoon of setup. The first time it points you at the exact query causing your checkout slowdown, it pays for itself.
If you are a founder deciding who to hire, ask your candidate how they monitor production. A developer who can talk through traces, sampling, and span attributes is a different level than one who only knows console.log. I have written more on this in my guide to hiring a Next.js developer.
FAQ
Does OpenTelemetry work with Next.js App Router and Server Components?
Yes. Next.js wraps server component renders and route handlers in spans automatically once you register the OTel SDK in instrumentation.ts. The App Router is well supported on the Node.js runtime. Edge runtime is the exception, with limited support.
Do I need a paid APM tool to use OpenTelemetry with Next.js?
No. You can self-host Grafana Tempo, ClickStack, or Jaeger and run the OTel Collector on a modest server. For most apps this is far cheaper than a vendor APM at scale. Vendor tools (Sentry, Dynatrace) are convenient but not required.
Why are my Next.js traces not showing up in the backend?
Check four things in order: that instrumentation.ts is actually loading (Next.js 15 runs it by default, older configs need the experimental flag), that your OTEL_EXPORTER_OTLP_ENDPOINT is correct and reachable, that there is only one @opentelemetry/api version in your tree, and that your batch processor flushes before the process exits.
Can OpenTelemetry in Next.js trace client-side performance too?
Server-side tracing is the strong suit. For browser telemetry you need separate client instrumentation (@opentelemetry/sdk-trace-web plus fetch/XHR instrumentation) and a way to correlate trace IDs between client and server. It is doable but adds complexity, so start server-side and add client tracing only if you have a specific need.
If you are building a Next.js app and want observability that actually answers questions instead of adding noise, that is the kind of work I do. I have shipped 300+ web apps and automation systems for teams in Bangladesh, the USA, the UK, and Australia, and I am happy to review your setup or build it with you. Reach out through the contact page and tell me what is slow. I will tell you whether tracing will help or whether you just need an index.
Frequently asked questions
Does OpenTelemetry work with Next.js App Router and Server Components?
Yes. Next.js wraps server component renders and route handlers in spans automatically once you register the OTel SDK in instrumentation.ts. The App Router is well supported on the Node.js runtime. The Edge runtime is the exception, with limited support and no full auto-instrumentation.
Do I need a paid APM tool to use OpenTelemetry with Next.js?
No. You can self-host Grafana Tempo, ClickStack, or Jaeger and run the OTel Collector on a modest server. For most apps this is far cheaper than a vendor APM at scale. Vendor tools like Sentry or Dynatrace are convenient but not required.
Why are my Next.js traces not showing up in the backend?
Check four things in order: that instrumentation.ts is actually loading (Next.js 15 runs it by default, older configs need the experimental flag), that your OTEL_EXPORTER_OTLP_ENDPOINT is correct and reachable, that there is only one @opentelemetry/api version in your dependency tree, and that your batch processor flushes before the process exits.
Can OpenTelemetry in Next.js trace client-side performance too?
Server-side tracing is the strong suit. For browser telemetry you need separate client instrumentation (@opentelemetry/sdk-trace-web plus fetch/XHR instrumentation) and a way to correlate trace IDs between client and server. It is doable but adds complexity, so start server-side and add client tracing only if you have a specific need.