What OpenTelemetry Gives a Website
OpenTelemetry (OTel) is a vendor-neutral standard for producing telemetry: traces (a timed tree of operations), logs and events (timestamped records), and metrics (aggregated numbers). You instrument your code once against the OpenTelemetry API, send the data over the OpenTelemetry Protocol (OTLP), and choose or change the backend later without touching application code.
For a website, the useful part is that one trace can start in the visitor's browser and continue on your server. A slow checkout click stops being two unrelated numbers (a browser timing and a server log line) and becomes one waterfall that shows where the time went.
| Signal | Produced where | Example on a website | Browser SDK support (Nov 2026) |
|---|---|---|---|
| Traces | Browser and server | documentLoad, GET /api/quote, pricing.calculate_quote | Yes |
| Log events | Browser and server | browser.web_vital (LCP, INP, CLS), browser.navigation, unhandled errors | Yes |
| Metrics | Server | request rate, queue depth | Not in the browser SDK yet; use the Node SDK or derive metrics in the backend |
This guide builds the whole pipeline: the browser SDK in a Next.js App Router site, server tracing with the Node SDK, an OpenTelemetry Collector in the middle, and Jaeger to look at the result. The Collector config and browser setup apply to any website; only the two instrumentation files are Next.js-specific.

Which Packages to Use (November 2026)
OpenTelemetry JavaScript changed shape in 2026, and most tutorials still show the old packages. Three changes matter:
- SDK 3.0 shipped on 20 October 2026.
@opentelemetry/sdk-trace-base,sdk-trace-webandsdk-trace-nodeare deprecated on npm with the message "Use @opentelemetry/sdk-trace package". Samplers and processors now import from@opentelemetry/sdk-trace. - Browser instrumentation moved to its own project, opentelemetry-browser. It ships
@opentelemetry/browser-sdk(a one-call setup) and@opentelemetry/browser-instrumentation, whose instrumentations are imported from./experimental/*subpaths. Both are marked experimental, so pin exact versions. - `@opentelemetry/api` 1.10 is required by the 3.x SDK and by the browser packages. The browser SDK imports the
logsAPI from@opentelemetry/api, which only exists from 1.10.0; an app on 1.9.x fails to bundle.
The versions below were installed together and tested end to end for this guide:
| Package | Version | Used for |
|---|---|---|
@opentelemetry/api | 1.10.0 | Creating custom spans; shared peer of everything below |
@opentelemetry/browser-sdk | 0.9.1 | startBrowserSdk() in the browser |
@opentelemetry/browser-instrumentation | 0.12.1 | Document load, navigation, Web Vitals, errors, fetch |
@opentelemetry/sdk-node | 0.301.2 | NodeSDK on the server |
@opentelemetry/sdk-trace | 3.1.1 | Samplers (ParentBasedSampler, TraceIdRatioBasedSampler) |
@opentelemetry/exporter-trace-otlp-http | 0.301.2 | OTLP/HTTP span export from Node |
@opentelemetry/resources | 3.1.1 | resourceFromAttributes() |
@opentelemetry/semantic-conventions | 1.45.0 | ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION |
| OpenTelemetry Collector (contrib) | 0.166.0 | Receiving, scrubbing, batching, exporting |
| Jaeger | 2.23.0 | Viewing traces locally |
npm install --save-exact \ @opentelemetry/api@1.10.0 \ @opentelemetry/browser-sdk@0.9.1 \ @opentelemetry/browser-instrumentation@0.12.1 \ @opentelemetry/sdk-node@0.301.2 \ @opentelemetry/sdk-trace@3.1.1 \ @opentelemetry/exporter-trace-otlp-http@0.301.2 \ @opentelemetry/resources@3.1.1 \ @opentelemetry/semantic-conventions@1.45.0Two compatibility traps showed up while testing:
- Node.js 22.15 or later. The 3.x packages declare
"node": ">=22.15.0". On Node 22.12, npm printsEBADENGINEwarnings for every OTel package. - Don't mix 2.x and 3.x packages.
@opentelemetry/resources@2.xdeclares@opentelemetry/api>=1.3.0 <1.10.0, so installing it next toapi@1.10.0fails withERESOLVE. Unpinned installs make this worse:npm install @opentelemetry/sdk-tracewith api 1.10 resolved to the old 2.12.1 line and failed. Pin every package to the same release line.
@vercel/otel is the shortcut the Next.js docs recommend, but version 2.3.0 (5 November 2026) still declares peer ranges for the 2.x SDK (@opentelemetry/resources <3.0.0, sdk-trace-base <3.0.0). If you want the new browser SDK, which needs api 1.10 and the 3.x packages, configure the Node SDK yourself as shown below. The bundled Next.js 16.3 docs also still import SimpleSpanProcessor from the deprecated @opentelemetry/sdk-trace-node.
Step 1: Run a Collector and Jaeger Locally
Send telemetry to a Collector, not straight to a vendor. The Collector is where you add CORS for browsers, delete personal data, batch exports and switch backends, all without redeploying the website.
Start with two containers: the Collector receiving OTLP/HTTP on port 4318, and Jaeger as the trace backend.
# compose.yamlservices: collector: image: otel/opentelemetry-collector-contrib:0.166.0 command: ["--config=/etc/otelcol/config.yaml"] volumes: - ./collector.yaml:/etc/otelcol/config.yaml:ro ports: - "4318:4318" # OTLP/HTTP from browsers and Node - "13133:13133" # health check depends_on: [jaeger] jaeger: image: jaegertracing/jaeger:2.23.0 ports: - "16686:16686" # Jaeger UIThe Collector config defines one pipeline per signal. Browsers send traces to /v1/traces and Web Vitals to /v1/logs, so both pipelines are needed:
# collector.yamlreceivers: otlp: protocols: http: endpoint: 0.0.0.0:4318 cors: allowed_origins: - http://localhost:3000 - https://www.example.com allowed_headers: ["*"] max_age: 7200processors: memory_limiter: check_interval: 1s limit_percentage: 80 spike_limit_percentage: 20 attributes/scrub: actions: - key: enduser.id action: delete - key: user.email action: delete batch: send_batch_size: 1024 timeout: 5sexporters: otlp_grpc/jaeger: endpoint: jaeger:4317 tls: insecure: true debug: verbosity: basicextensions: health_check: endpoint: 0.0.0.0:13133service: extensions: [health_check] pipelines: traces: receivers: [otlp] processors: [memory_limiter, attributes/scrub, batch] exporters: [otlp_grpc/jaeger, debug] logs: receivers: [otlp] processors: [memory_limiter, attributes/scrub, batch] exporters: [debug]docker compose up -dcurl -s localhost:13133 # {"status":"Server available",...}Exporter names changed. Collector 0.166.0 lists the OTLP exporters as otlp_grpc and otlp_http. Older configs and tutorials use otlp and otlphttp; run otelcol-contrib components against the image you deploy to see the names it accepts.

Step 2: Instrument the Next.js Server
Next.js runs register() from instrumentation.ts once when a server instance starts. NodeSDK only works in the Node.js runtime, so import it conditionally from a separate file. With a src/ folder, both files go in src/, next to app/.
// src/instrumentation.tsexport async function register() { if (process.env.NEXT_RUNTIME === "nodejs") { await import("./instrumentation.node"); }}// src/instrumentation.node.tsimport { NodeSDK } from "@opentelemetry/sdk-node";import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";import { resourceFromAttributes } from "@opentelemetry/resources";import { ParentBasedSampler, TraceIdRatioBasedSampler } from "@opentelemetry/sdk-trace";import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION,} from "@opentelemetry/semantic-conventions";// Traces only: without these, sdk-node also tries to export metrics and logs.process.env.OTEL_METRICS_EXPORTER ??= "none";process.env.OTEL_LOGS_EXPORTER ??= "none";const sdk = new NodeSDK({ resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: "web-server", [ATTR_SERVICE_VERSION]: process.env.APP_VERSION ?? "dev", "deployment.environment.name": process.env.NODE_ENV, }), traceExporter: new OTLPTraceExporter({ // Defaults to http://localhost:4318/v1/traces; override with OTEL_EXPORTER_OTLP_ENDPOINT. }), // Keep the browser's sampling decision; sample 20% of traces that start here. sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(0.2) }),});sdk.start();process.on("SIGTERM", () => { sdk.shutdown().finally(() => process.exit(0));});Point the exporter at the Collector with standard environment variables, so the same build works in every environment:
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 APP_VERSION=1.4.2 npm run startYou don't need an HTTP instrumentation package for incoming requests. Next.js already emits its own spans (instrumentation scope next.js): a root GET /api/quote span with http.route, next.route and http.status_code, plus executing api route (app) /api/quote, resolve page components and start response. Set NEXT_OTEL_VERBOSE=1 to see more spans, and NEXT_OTEL_FETCH_DISABLED=1 if you replace Next's server-side fetch spans with your own instrumentation.
The OTEL_METRICS_EXPORTER and OTEL_LOGS_EXPORTER lines matter. The OpenTelemetry environment variable spec defaults both to otlp, so the Node SDK also tries to push metrics and logs to the same endpoint. If your Collector has no metrics pipeline, you get a steady stream of export errors in the server log.
Step 3: Add Custom Spans for Business Logic
Framework spans tell you which route was slow. Custom spans tell you why. Wrap the operations you would otherwise debug with console.time: database queries, payment calls, cache lookups, third-party APIs.
A small helper keeps the try/catch/end pattern in one place, so a span is never left open and errors are always recorded:
// src/lib/tracer.tsimport { SpanStatusCode, trace, type Span } from "@opentelemetry/api";const tracer = trace.getTracer("web-server");export function withSpan<T>(name: string, fn: (span: Span) => Promise<T>): Promise<T> { return tracer.startActiveSpan(name, async (span) => { try { const result = await fn(span); span.setStatus({ code: SpanStatusCode.OK }); return result; } catch (error) { span.recordException(error as Error); span.setStatus({ code: SpanStatusCode.ERROR, message: String(error) }); throw error; } finally { span.end(); } });}// src/app/api/quote/route.tsimport { withSpan } from "@/lib/tracer";export async function GET(request: Request) { const sku = new URL(request.url).searchParams.get("sku") ?? "unknown"; const quote = await withSpan("pricing.calculate_quote", async (span) => { span.setAttribute("app.sku", sku); await new Promise((r) => setTimeout(r, 40)); // stand-in for a DB call return { sku, total: 49 }; }); return Response.json(quote);}Because startActiveSpan makes the new span the active context, it automatically becomes a child of the Next.js route span, and any span created inside fn becomes its child.
Naming rules that keep traces searchable:
- Name spans after the operation, not the data:
pricing.calculate_quote, notquote for shirt-42. Put variable values in attributes. - Prefix your own attributes (
app.sku) so they never collide with semantic convention names. - Never put emails, tokens or full card numbers in attributes. The Collector scrub step is a safety net, not the main control.
Step 4: Instrument the Browser
instrumentation-client.ts runs in the browser before the app becomes interactive, which is what the browser SDK wants: it should start before other libraries patch fetch or history. Next.js warns in development if this file takes longer than 16 ms to initialize, so keep it to SDK setup only.
// src/instrumentation-client.tsimport { startBrowserSdk } from "@opentelemetry/browser-sdk";import { DocumentLoadInstrumentation } from "@opentelemetry/browser-instrumentation/experimental/document-load";import { ErrorsInstrumentation } from "@opentelemetry/browser-instrumentation/experimental/errors";import { FetchInstrumentation } from "@opentelemetry/browser-instrumentation/experimental/fetch";import { NavigationInstrumentation } from "@opentelemetry/browser-instrumentation/experimental/navigation";import { WebVitalsInstrumentation } from "@opentelemetry/browser-instrumentation/experimental/web-vitals";import { ParentBasedSampler, TraceIdRatioBasedSampler } from "@opentelemetry/sdk-trace";const collector = process.env.NEXT_PUBLIC_OTEL_COLLECTOR_URL; // e.g. https://otel.example.comconst sampleRate = Number(process.env.NEXT_PUBLIC_OTEL_TRACE_SAMPLE_RATE ?? "0.1");if (collector) { try { startBrowserSdk({ serviceName: "web-browser", serviceVersion: process.env.NEXT_PUBLIC_APP_VERSION ?? "dev", resourceAttributes: { "deployment.environment.name": process.env.NODE_ENV }, traces: { exportConfig: { url: `${collector}/v1/traces` }, sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(sampleRate) }), }, logs: { exportConfig: { url: `${collector}/v1/logs` } }, instrumentations: [ new DocumentLoadInstrumentation(), new NavigationInstrumentation({ useNavigationApiIfAvailable: true }), new WebVitalsInstrumentation(), new ErrorsInstrumentation(), new FetchInstrumentation({ // Same-origin requests get traceparent automatically; list other origins you own. propagateTraceHeaderCorsUrls: [/^https:\/\/api\.example\.com\//], ignoreUrls: [new RegExp(`^${collector}`)], }), ], }); } catch (error) { // Telemetry must never break the page. console.warn("OpenTelemetry browser SDK failed to start", error); }}# .env.productionNEXT_PUBLIC_OTEL_COLLECTOR_URL=https://otel.example.comNEXT_PUBLIC_OTEL_TRACE_SAMPLE_RATE=0.1NEXT_PUBLIC_APP_VERSION=1.4.2Details that are easy to get wrong:
- Per-signal URLs.
exportConfig.urlinsidetracesandlogsis the full URL; the SDK does not append/v1/tracesfor you. A single top-levelexportConfigwould send every signal to the same path. - An invalid URL disables everything. If
urlis not an absolute http(s) URL, the SDK logsdiag.errorand returns a no-op SDK withinvalidConfig: trueinstead of throwing. Check that flag in a smoke test. - Don't mix instrumentation families. The new browser instrumentations cannot detect patches made by the classic
@opentelemetry/instrumentation-fetchor-document-loadpackages, so loading both records every request twice. - Bundler support. The 3.x packages resolve platform code through
#platformsubpath imports. Next.js 16 with Turbopack built this setup without changes; webpack needs 5.54 or later, and Jest needs 29.4 or later if tests import the SDK.
Leaving NEXT_PUBLIC_OTEL_COLLECTOR_URL unset turns browser telemetry off completely, which is what you want in local development and preview builds that shouldn't report.
Step 5: Connect Browser and Server Into One Trace
Distributed tracing works because FetchInstrumentation adds a W3C Trace Context traceparent header to outgoing requests, and the Node SDK continues the trace it describes. In the test run for this guide, the browser sent:
traceparent: 00-d9d60cbf1f46c8f71e99b5dfe6162dec-006bfca2a08b90c8-01 | | | | | trace ID (shared by every span) parent span ID flags: 01 = sampled versionJaeger then showed one trace, two services and six spans for a single button click:

| Span | Service | Duration | Created by |
|---|---|---|---|
GET | web-browser | 49 ms | browser-instrumentation/fetch |
GET /api/quote | web-server | 48 ms | Next.js (BaseServer.handleRequest) |
resolve page components | web-server | 0 ms | Next.js |
executing api route (app) /api/quote | web-server | 41 ms | Next.js |
pricing.calculate_quote | web-server | 40 ms | Custom span from Step 3 |
start response | web-server | 0 ms | Next.js |
The gap between the 49 ms browser span and the 48 ms server span is network and queueing time. On a real deployment that gap is often the most useful number in the trace.
Three settings decide whether the header reaches the server:
- Same-origin requests (
/api/...) gettraceparentautomatically. - Cross-origin APIs you own must match
propagateTraceHeaderCorsUrls, and that API's CORS policy must allow the header:Access-Control-Allow-Headers: traceparent, tracestate. Without it, the browser's preflight fails and the real request breaks, not just the trace. Never use/.*/here; it sends your trace IDs to every third-party API and breaks third parties that reject unknown headers. - Content Security Policy. The browser posts telemetry to the Collector origin, so add it to
connect-src, for exampleconnect-src 'self' https://otel.example.com. A strict CSP without it blocks every export silently; see the strict CSP guide.
The Collector's CORS list works the other way round. In testing, a preflight from an allowed origin returned 204 with Access-Control-Allow-Origin: http://localhost:3100. A preflight from an unlisted origin also returned 204, but with no Access-Control-Allow-Origin header, so the browser drops the export. A 204 in the network tab doesn't prove the origin is allowed; check for that header.
Sampling: Keep Costs Predictable
A busy site produces far more traces than anyone will read. Head sampling decides at the start of a trace whether to record it, and every service downstream follows that decision through the traceparent flag.

The setup in this guide uses two samplers that work together:
| Where | Sampler | Effect |
|---|---|---|
| Browser | ParentBasedSampler({ root: TraceIdRatioBasedSampler(0.1) }) | Records 10% of traces that start in the browser |
| Server | ParentBasedSampler({ root: TraceIdRatioBasedSampler(0.2) }) | Follows the browser's flag when traceparent is present; otherwise records 20% |
TraceIdRatioBasedSampler decides from the trace ID itself. Any service that sees the same trace ID at the same ratio reaches the same answer, and a trace sampled at 10% is also sampled at any higher percentage.
Things to know before choosing rates:
- Web Vitals are not sampled by the trace sampler. They are log events, so every page view reports them. Thin them out in the Collector if the volume is a problem, not by lowering the trace ratio.
- Unsampled spans are still created, just not recorded or exported. Instrumentation overhead stays; network and storage costs drop.
- Errors in unsampled traces are lost with head sampling. If you need every failed request, look at tail sampling in the Collector (
tail_samplingprocessor), which decides after the whole trace has arrived. It needs all spans of a trace to reach the same Collector instance, so plan for that before scaling out.
Start with 10% in the browser and 100% on the server for low-traffic sites. Lower the rates once you see real export volume in the Collector's debug output or your backend's billing page.
Privacy, Consent and Personal Data
Browser telemetry is data about your visitors, so treat it like analytics. In the EU and UK that usually means consent before you collect anything that isn't strictly necessary. The browser SDK supports this directly: start it disabled and switch the instrumentations on when the visitor agrees.
import { startBrowserSdk } from "@opentelemetry/browser-sdk";import { WebVitalsInstrumentation } from "@opentelemetry/browser-instrumentation/experimental/web-vitals";const sdk = startBrowserSdk({ enabled: false, // nothing is collected until the visitor opts in serviceName: "web-browser", traces: { exportConfig: { url: "https://otel.example.com/v1/traces" } }, logs: { exportConfig: { url: "https://otel.example.com/v1/logs" } }, instrumentations: [new WebVitalsInstrumentation()],});export function onAnalyticsConsentChange(granted: boolean) { if (granted) sdk.enable(); else sdk.disable();}Two caveats from the SDK's own documentation: consent covers the instrumentations only, so spans you create manually are still recorded and exported; and disable() doesn't drop data that was already recorded. Gate your own manual spans behind the same consent flag.
Limit personal data at three layers:
- At the source. The document-load instrumentation redacts credentials and common secret query parameters (
token,api_key,password, signed URL signatures) withdefaultSanitizeUrl. Navigation, Web Vitals, fetch and XHR instrumentations take asanitizeUrloption: composedefaultSanitizeUrlwith a function that also removes your own sensitive parameters, such as emails or reset tokens. - In the Collector. The
attributes/scrubprocessor deletes keys likeuser.emailandenduser.idbefore anything reaches a backend. Add every key your team might set by accident. - In resources. The Node SDK's default resource detectors attach
host.name,process.command_argsandprocess.ownerto every server span. That's harmless on a container, but on a shared host it can expose paths and usernames. Review one exported span before you choose a vendor.
Running It in Production
The local Compose setup becomes a production pipeline with a few changes.
Expose the Collector over HTTPS on its own hostname (for example otel.example.com), behind your existing reverse proxy or load balancer. Browsers will only send to it if the page is HTTPS and the Collector is too. Allow only POST and OPTIONS to /v1/traces and /v1/logs from the internet, and keep ports 4317 and 13133 private.
Don't put vendor API keys in the browser. Anything in NEXT_PUBLIC_* is public. The browser sends unauthenticated OTLP to your Collector, and the Collector adds the vendor credential on the way out:
exporters: otlp_http/vendor: endpoint: https://otlp.vendor.example headers: authorization: "Bearer ${env:VENDOR_API_KEY}"Protect the public endpoint. Anyone can post to an open OTLP receiver. Keep the CORS allow-list tight, rate-limit the hostname at the proxy, and keep memory_limiter as the first processor, so a flood makes the Collector refuse data early instead of running out of memory.
Self-hosted Node or Docker. NodeSDK with a batch exporter fits a long-running server. Send SIGTERM on deploys so the shutdown handler flushes the last batch. The Docker + Nginx deployment guide covers the container side.
Vercel. Next.js documents @vercel/otel for Vercel deployments, and Vercel can forward traces to an observability provider (see Vercel's tracing documentation). At the time of writing, @vercel/otel 2.3.0 targets the 2.x SDK, so it won't share a dependency tree with the 3.x browser SDK without peer-dependency conflicts. Pick one path per app: keep @vercel/otel on the server and hold the browser on the previous generation of packages, or use the manual NodeSDK setup from this guide and test that spans from short-lived function instances reach the Collector before you rely on them.
Version everything. Set service.version on both sides (APP_VERSION, NEXT_PUBLIC_APP_VERSION) from your build, for example the git SHA. Comparing p75 INP before and after a release is then a single filter.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
npm ERR! ERESOLVE mentioning @opentelemetry/api@">=1.3.0 <1.10.0" | A 2.x package next to api@1.10.0 | Pin every OTel package to the 3.x line (table in the packages section) |
Build error: missing export logs from @opentelemetry/api | api 1.9.x installed | Install @opentelemetry/api@1.10.0 |
Build error resolving #platform | Old bundler (webpack 4, Jest < 29.4) | Upgrade the bundler or test runner |
| Browser exports blocked, console shows a CORS error | Page origin missing from cors.allowed_origins | Add the exact origin, including scheme and port |
| Browser exports blocked with no CORS error | CSP connect-src doesn't include the Collector | Add the Collector origin to connect-src |
| Browser and server spans appear as two separate traces | traceparent not sent or not accepted | Check the request headers in DevTools; for cross-origin APIs add them to propagateTraceHeaderCorsUrls and allow the header in CORS |
| Cross-origin API calls start failing after adding OTel | API CORS doesn't allow traceparent | Allow traceparent, tracestate in Access-Control-Allow-Headers, or remove that origin from propagateTraceHeaderCorsUrls |
| Server log fills with metrics or log export errors | OTEL_METRICS_EXPORTER / OTEL_LOGS_EXPORTER default to otlp | Set them to none, or add matching pipelines to the Collector |
Collector fails to start: unknown exporter otlp | New component names | Use otlp_grpc or otlp_http |
| Every request appears twice | Classic and new browser instrumentations both loaded | Remove @opentelemetry/instrumentation-fetch and friends |
| No browser data at all, no errors | Collector URL not set at build time, or invalid | NEXT_PUBLIC_* values are inlined at build; rebuild after changing them |
Use the debug exporter while setting up. With verbosity: detailed, the Collector prints every span and log record with all attributes, which is the fastest way to confirm what the browser actually sent.
Production Checklist
- All OpenTelemetry packages pinned to one release line (3.x with
@opentelemetry/api@1.10.0) on Node.js 22.15 or later. - Collector reachable over HTTPS, CORS limited to your own origins,
memory_limiterfirst andbatchlast in every pipeline. instrumentation.tsstartsNodeSDKonly whenNEXT_RUNTIME === "nodejs", with metrics and logs exporters disabled unless the Collector accepts them.instrumentation-client.tsstarts the browser SDK insidetry/catch, with per-signal export URLs and a sample rate taken from configuration.traceparentpropagated only to origins you own, and those APIs allow the header in CORS.- Collector origin added to CSP
connect-src. - Consent wired to
sdk.enable()/sdk.disable()where the law requires it, with manual spans behind the same flag. - PII scrubbed in the Collector, plus URL sanitizing in the browser.
service.versionset from the build on both browser and server.- One end-to-end test passed: click a button, find the trace in the backend, and confirm the browser span is the parent of the server span.