Frontend to Backend Tracing with the OpenTelemetry session.id
A trace shows one request. A session replay shows one visit. With one ID carried from the browser to every service, you can jump from a user's click to the exact log line that failed, and back. Here is the setup, in about 60 lines of code.
Dmytro Vavreniuk
Product Engineer
Short version: frontend to backend tracing needs two IDs. trace_id (sent as traceparent) links one browser request to its backend trace. The OpenTelemetry session.id (sent as W3C baggage) links every request of a visit to the session replay. Use the ID your replay recorder already has, send both headers only to your own APIs, allow them in CORS, and add a baggage span and log processor on the backend. Then one query by session.id returns the user's replay, every trace and every log line of that visit.
Most teams already have both halves. The frontend team watches session replays and sees a user click "Pay" three times. The backend team has traces and structured logs and sees a spike of 422 errors. Joining the two usually means copying a timestamp from one tool into the other and hoping the clocks agree. That works for one bug a week. It does not work when an AI agent investigates incidents across hundreds of sessions, because timestamp matching at scale produces confident wrong answers.
OpenTelemetry has had a session.id attribute for a while. What changed this autumn is that the browser side of OpenTelemetry started to settle around it, and replay tools started to read it.
What changed in October 2026
| Date | What happened |
|---|---|
| Oct 27, 2026 | First release (v0.1.0-dev) of the OpenTelemetry client-side semantic conventions: browser events, plus enduser.id and enduser.pseudo.id moved out of the core registry. |
| Oct 29, 2026 | Browser SIG meeting: sending session.id to downstream services gets a "yes", with W3C Baggage as the common pattern. Community notes stress that no formal decision or spec PR exists yet. |
| Oct 30, 2026 | @opentelemetry/browser-sdk 0.7.0 ships. Breaking: no default HTTP exporter any more, and instrumentations move to a browser-native InstrumentationBase. |
| Oct 30, 2026 | ClickStack (HyperDX) merges support for the OpenTelemetry session.id, so its session replays line up with OTel traces and logs. |
| Autumn 2026 | Grafana Cloud Frontend Observability opens a Session Replay public preview on top of its OpenTelemetry-based Faro SDK. |
Sources: the session semantic conventions, the browser-sdk 0.7.0 release, community notes from the 29 October Browser SIG and the ClickStack change. We covered the replay side of this shift in open-source vs SaaS session replay tools. The direction is clear even though the spec is not final: session.id is becoming the join key between frontend and backend telemetry, and W3C Baggage is the way it travels. You can set this up today with stable building blocks and swap in the official browser SDK pieces as they mature.
trace_id and session.id: two IDs, two jobs
| ID | Covers | Created by | Travels in | Answers |
|---|---|---|---|---|
trace_id | One request and everything it triggers | Browser or first service, per request | traceparent header (W3C Trace Context) | Which services did this request touch and where did it fail? |
session.id | One visit: many pages, many requests | Browser, by the replay recorder or OTel browser SDK | baggage header (W3C Baggage), or a custom header | What did this user do before, during and after the failure? |
You need both. trace_id alone gives you a perfect picture of one failing request and nothing about the user who sent it. session.id alone groups everything a user did, but cannot tell you which of fifty backend spans belongs to which click. Together they turn "a user says checkout is broken" into a lookup.
The architecture in four hops
- Browser. The replay recorder owns the session ID. The OTel browser SDK reads it, stamps it on browser spans and adds it to the
baggageheader next totraceparent. - Edge. Your API gateway or load balancer allows the headers in CORS and passes them through.
- Services. OTel SDKs extract trace context and baggage automatically. A baggage processor copies
session.idonto every span and log record, and outgoing calls forward both headers to the next service. - Backend. Traces and logs land in Tempo, Loki, ClickHouse or any OTLP backend with
session.idas an attribute. The replay tool links to them by the same ID.
Step 1: the browser
The most common mistake is to end up with two session IDs: one from the replay recorder and one from the OpenTelemetry SDK. Pick the recorder's ID, because that is the one your replays are stored under. The setup below uses the stable OpenTelemetry JS web packages. It adds session.id to every browser span and to the baggage header of every traced request to your API:
// browser/otel.ts - one session ID for the replay AND for OpenTelemetry
import { context, propagation } from '@opentelemetry/api';
import { WebTracerProvider, BatchSpanProcessor } from '@opentelemetry/sdk-trace-web';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { CompositePropagator, W3CTraceContextPropagator, W3CBaggagePropagator } from '@opentelemetry/core';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
// Use the ID your session replay recorder already created. Do not invent a second one.
const getSessionId = (): string => window.__replaySessionId ?? 'unknown';
// 1. Put session.id on every browser span
const sessionSpanProcessor = {
onStart(span) { span.setAttribute('session.id', getSessionId()); },
onEnd() {}, forceFlush: () => Promise.resolve(), shutdown: () => Promise.resolve(),
};
// 2. Put session.id into the W3C baggage header of every traced request
const baggage = new W3CBaggagePropagator();
const sessionBaggagePropagator = {
inject(ctx, carrier, setter) {
const bag = (propagation.getBaggage(ctx) ?? propagation.createBaggage())
.setEntry('session.id', { value: getSessionId() });
baggage.inject(propagation.setBaggage(ctx, bag), carrier, setter);
},
extract: (ctx) => ctx,
fields: () => baggage.fields(),
};
const provider = new WebTracerProvider({
spanProcessors: [
sessionSpanProcessor, // must run before the exporting processor
new BatchSpanProcessor(new OTLPTraceExporter({ url: 'https://otel.example.com/v1/traces' })),
],
});
provider.register({
propagator: new CompositePropagator({
propagators: [new W3CTraceContextPropagator(), sessionBaggagePropagator],
}),
});
registerInstrumentations({
instrumentations: [
new FetchInstrumentation({
// Only YOUR APIs get traceparent + baggage. Never third parties.
propagateTraceHeaderCorsUrls: [/^https:\/\/api\.example\.com\//],
}),
],
});Two details matter. getSessionId() is called on every span and request, not once at page load, so a session that rotates after 30 minutes of inactivity is picked up immediately. And propagateTraceHeaderCorsUrls is a strict allow-list: payment providers, analytics and CDNs must never receive your headers. If you are trying the new @opentelemetry/browser-sdk instead, it already manages sessions and sets the attribute, but you still need the baggage step, and since 0.7.0 you must configure the exporter explicitly.
No OpenTelemetry in the browser yet?
You can still get most of the value. Send the session ID as baggage with a small fetch wrapper; any OpenTelemetry-instrumented backend will pick it up exactly as if the browser SDK had sent it:
// No OpenTelemetry in the browser yet? A fetch wrapper is enough to start.
const API = 'https://api.example.com/';
const originalFetch = window.fetch;
window.fetch = (input, init = {}) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
if (!url.startsWith(API)) return originalFetch(input, init); // first-party APIs only
const headers = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined));
const entry = 'session.id=' + encodeURIComponent(window.__replaySessionId);
const existing = headers.get('baggage');
headers.set('baggage', existing ? existing + ',' + entry : entry);
return originalFetch(input, { ...init, headers });
};Step 2: allow the headers at the edge
If the frontend and the API live on different origins, the browser sends a CORS preflight for any request with custom headers. Until the API allows traceparent, tracestate and baggage, those requests fail, which is a good reason to roll this out on staging first:
# nginx in front of the API: let the browser send the propagation headers
add_header Access-Control-Allow-Origin "https://app.example.com" always;
add_header Access-Control-Allow-Headers "content-type, authorization, traceparent, tracestate, baggage" always;
# Express alternative
app.use(cors({
origin: 'https://app.example.com',
allowedHeaders: ['content-type', 'authorization', 'traceparent', 'tracestate', 'baggage'],
}));The edge is also the right place to defend yourself. Baggage is input from the internet: cap its size (the W3C spec allows up to 8,192 bytes, you need about 60), and if your gateway can, keep only the session.id entry from external requests.
Step 3: copy session.id onto spans and logs
OpenTelemetry SDKs extract baggage from incoming requests by default, but they do not turn it into attributes. That is the job of the baggage processors in the contrib repositories. Each one takes a predicate, so you copy only session.id and nothing else a caller might send.
Node.js
// Node.js: copy session.id from baggage onto every span and OTel log record
import { NodeSDK } from '@opentelemetry/sdk-node';
import { BaggageSpanProcessor } from '@opentelemetry/baggage-span-processor';
import { BaggageLogRecordProcessor } from '@opentelemetry/baggage-log-record-processor';
const onlySessionId = (key: string) => key === 'session.id';
const sdk = new NodeSDK({
serviceName: 'checkout-api',
spanProcessors: [new BaggageSpanProcessor(onlySessionId) /* + your exporter */],
logRecordProcessors: [new BaggageLogRecordProcessor(onlySessionId) /* + your exporter */],
});
sdk.start();
// Logging to stdout with pino instead? Add it in a mixin:
import pino from 'pino';
import { context, propagation, trace } from '@opentelemetry/api';
export const logger = pino({
mixin() {
const ctx = context.active();
return {
trace_id: trace.getSpanContext(ctx)?.traceId,
'session.id': propagation.getBaggage(ctx)?.getEntry('session.id')?.value,
};
},
});Python
# Python: pip install opentelemetry-processor-baggage
from opentelemetry.processor.baggage import BaggageSpanProcessor, BaggageLogProcessor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk._logs import LoggerProvider
only_session_id = lambda key: key == "session.id"
tracer_provider = TracerProvider()
tracer_provider.add_span_processor(BaggageSpanProcessor(only_session_id))
# ... then your BatchSpanProcessor(OTLPSpanExporter())
logger_provider = LoggerProvider()
logger_provider.add_log_record_processor(BaggageLogProcessor([only_session_id]))Go
// Go: go get go.opentelemetry.io/contrib/processors/baggagecopy
import (
"go.opentelemetry.io/contrib/processors/baggagecopy"
"go.opentelemetry.io/otel/baggage"
sdklog "go.opentelemetry.io/otel/sdk/log"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
onlySessionID := func(m baggage.Member) bool { return m.Key() == "session.id" }
tp := sdktrace.NewTracerProvider(
sdktrace.WithSpanProcessor(baggagecopy.NewSpanProcessor(onlySessionID)),
sdktrace.WithBatcher(traceExporter),
)
lp := sdklog.NewLoggerProvider(
sdklog.WithProcessor(baggagecopy.NewLogProcessor(onlySessionID)),
sdklog.WithProcessor(sdklog.NewBatchProcessor(logExporter)),
)
// Plain slog to stdout? Read it from the request context:
sid := baggage.FromContext(r.Context()).Member("session.id").Value()
logger := slog.With("session.id", sid)The field names match the ones in our structured logging best practices guide, so session.id and trace_id look the same in every service whether logs go through OTLP or stdout. Services that call other services need nothing extra: the HTTP and gRPC instrumentations forward baggage automatically, which also means the next service gets session.id for free.
Step 4: query one session end to end
With the attribute in place, a session becomes a filter in every backend you use:
# Grafana Tempo (TraceQL): every trace of one session
{ span.session.id = "s_7f3c2a" }
# Grafana Loki (LogQL): OTLP attributes land as structured metadata, dots become underscores
{service_name=~".+"} | session_id = "s_7f3c2a"
# ClickHouse / ClickStack (default OTel schema)
SELECT Timestamp, ServiceName, SeverityText, Body
FROM otel_logs
WHERE LogAttributes['session.id'] = 's_7f3c2a'
ORDER BY Timestamp;Put the session first and the timeline reads like a story. This is the checkout incident from our AI debugging article, merged from the replay, the gateway and the pricing service by one ID:
09:14:01 replay s_7f3c2a click "Pay" on /checkout
09:14:01 browser s_7f3c2a POST /api/checkout/quote traceparent=00-4bf92f35... -> 422
09:14:01 gateway s_7f3c2a trace 4bf92f35... route=/checkout/quote dur=212ms
09:14:01 pricing s_7f3c2a level=error msg="quote validation failed" error.type=missing_billing_country
09:14:02 replay s_7f3c2a TypeError: Cannot read properties of undefined (reading 'amount')
09:14:09 replay s_7f3c2a click "Pay" again (rage click x3), session ends 09:15The link should work in both directions. From a replay in LogNroll, the failing network call shows its traceparent, so you can open the trace. From the backend, add a data link in Grafana or a tag in your error tracker that builds the replay URL from session.id, so an engineer looking at a stack trace can watch what the user did right before it. The same IDs are what makes the LogNroll MCP server useful to an agent: it reads the session, takes the IDs from the network calls and looks them up in your log and trace tools.
Pitfalls we see most often
| Problem | Fix |
|---|---|
| CORS preflight fails after enabling propagation | Add traceparent, tracestate and baggage to Access-Control-Allow-Headers on every API origin the browser calls. |
| Baggage leaks to third-party APIs | Limit propagateTraceHeaderCorsUrls (browser) to your own APIs. On the backend, HTTP instrumentation injects baggage into outgoing calls too, so keep only a random session ID in it. |
| Two different session IDs | The replay recorder and the OTel SDK each generate one. Pick one source (usually the recorder) and read it everywhere. |
| session.id as a metric or stream label | It has unbounded cardinality. Keep it as a span/log attribute or Loki structured metadata, never a Prometheus label or Loki stream label. |
| Head sampling drops the trace you need | session.id on log lines survives sampling. For traces, use tail sampling that keeps traces with errors, or sample by session so a session is all-in or all-out. |
| Session rotates mid-visit | Emit session.start with session.previous_id when the recorder rotates after inactivity, and read the ID at request time, not once at page load. |
| WebSockets and sendBeacon have no custom headers | Send the session.id in the first WebSocket message or in the beacon payload and add it to the span or log on the server. |
On privacy: a random session ID is pseudonymous, but under GDPR it is still personal data once it links to a recording. Keep the same retention for logs that carry it as for the replay, and mask inputs at capture time. Details in session replay and GDPR.
Rollout checklist
| Item | Quick test |
|---|---|
| One session ID source in the browser | The ID in a replay equals the session.id on the browser spans for the same visit. |
| Propagation reaches your API | DevTools > Network: your API calls carry traceparent and baggage; calls to Stripe or analytics do not. |
| CORS allows the headers | No preflight errors in the console after a fresh load. |
| Backend copies session.id | A server span for that request has a session.id attribute. |
| Logs carry session.id and trace_id | One log query by session.id returns lines from every service the visit touched. |
| Links both ways | From a replay you reach the trace; from a backend error you reach the replay. |
Frequently asked questions
What is the OpenTelemetry session.id?
session.id is the OpenTelemetry semantic convention attribute for a user session, defined together with session.previous_id and the session.start and session.end events. As of November 2026 these conventions are still in Development status. In browsers, the session usually covers one visit and is created by the RUM or session replay SDK.
How do I connect frontend sessions to backend traces?
Send two things from the browser with every call to your own API: the W3C traceparent header, which links the browser span to the backend trace, and the session.id in the W3C baggage header. On the backend, a baggage span processor and a baggage log processor copy session.id onto every span and log record, so you can query a whole session across services.
Should session.id travel in W3C Baggage or a custom header?
Baggage is the standard choice and is what the OpenTelemetry Browser SIG discussed in October 2026: OpenTelemetry SDKs propagate it through every service automatically. A custom header such as x-session-id is fine as a first step without OpenTelemetry, but you have to forward and log it by hand in each service.
Is it safe to put session.id in baggage?
A random session ID is a reasonable baggage value. Baggage is sent in plain HTTP headers and is forwarded to downstream calls, so never put emails, user names, tokens or internal user IDs in it, and only send it to your own APIs. Under GDPR a session ID is still pseudonymous personal data, so apply the same retention rules as for the replay itself.
Does the new OpenTelemetry browser SDK do this for me?
Partly. @opentelemetry/browser-sdk includes session management and sets the session.id attribute on its telemetry, but community notes on version 0.6.0 found that it does not write session.id into baggage, and since 0.7.0 it no longer configures a default exporter. Until propagation is decided in the spec, add the baggage step yourself as shown in this guide.
Further reading
- Structured logging best practices for Node.js, Python and Go
- AI agent debugging in production: logs, traces and session replay over MCP
- Open-source vs SaaS session replay tools in 2027
- Network debugging with session replay
- LogNroll product overview
See what the user did before every backend error. Try LogNroll for free and link replays to your traces by session.id.