Reading an OpenTelemetry span from globalThis returns null

I wrote about twenty lines of code in nextjs-logger for reading an OpenTelemetry span from globalThis, so that every log line would carry the current trace ID. I wrote a unit test for it. The test passed. I shipped it.
It never worked. Not once. Not in development, not in production, not in any app that had OpenTelemetry fully installed and running. The function returns null every single time, and because a missing trace ID is not an error, nothing ever told me.
The cause is one wrong assumption about what lives inside a global object. The test could not catch it, because I wrote the test from the same wrong assumption.
What I was trying to do
A quick bit of background, in plain words.
When one request moves through several services, you want every log line from all of them to carry the same ID. That ID is called a trace ID. Then, when something breaks, you search for one ID and get the whole story instead of five disconnected pieces.
There are two places that ID can come from:
- The
traceparentheader on the incoming request. I covered that half in an earlier post on request correlation, so I will not repeat it here. - The active span, if the app actually runs the OpenTelemetry SDK.
Source 2 is the better one when it exists, because it follows the span the app is in right now, not just the one it started with. (If you are sending logs onward rather than just printing them, I also wrote up the OTLP traps that still return 200.) This post is about source 2, and about how I got it wrong.
Why I read a global instead of importing the package
My logger is a library. If I import @opentelemetry/api, every app installing my logger has to install that too, even the apps that will never trace anything.
There is a documented way around this. The OpenTelemetry JS API puts itself on a well-known global key:
globalThis[Symbol.for('opentelemetry.js.api.1')]It does this on purpose, and it is written down in the API’s own global-utils source. Node projects often end up with two copies of the same package at slightly different versions, and two copies would otherwise mean two separate, invisible worlds. One shared global keeps them talking to each other.
So reading that global is a fair thing to do. My mistake was not that I read it. It was what I assumed was inside it.
The code I shipped
export function getActiveSpanContext(): { traceId: string; spanId: string } | null {
try {
const registry = (globalThis as Record<symbol, unknown>)[
Symbol.for('opentelemetry.js.api.1')
] as {
trace?: { getSpan?: (ctx: unknown) => { spanContext?: () => unknown } | undefined };
context?: { active?: () => unknown };
} | undefined;
const active = registry?.context?.active?.();
if (active === undefined) return null;
const span = registry?.trace?.getSpan?.(active);
const spanContext = span?.spanContext?.() as
| { traceId?: unknown; spanId?: unknown }
| undefined;
// ...validate and return
} catch {
return null;
}
}The logic reads fine. Get the active context, pull the span out of it, read the span’s IDs. That is genuinely how you do it when you import the package:
import { trace, context } from '@opentelemetry/api'
const span = trace.getSpan(context.active())I assumed the global held those same two objects under the same two names. It holds something else.
And here is the test that passed
it('reads the active span through the global API registry', () => {
globalThis[Symbol.for('opentelemetry.js.api.1')] = {
context: { active: () => ({}) },
trace: {
getSpan: () => ({ spanContext: () => ({ traceId: TRACE_ID, spanId: SPAN_ID }) }),
},
}
expect(getActiveSpanContext()).toEqual({ traceId: TRACE_ID, spanId: SPAN_ID })
})Green. Every time.
Look closely at what that test actually proves. I invented a fake object, shaped exactly the way I guessed the real one was shaped. Then I checked that my code could read my own fake. It could. That is all this test ever measured.
The real package was never in the room.
What is actually in there
So I installed OpenTelemetry for real and just printed the thing:
const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node')
new NodeTracerProvider().register()
const reg = globalThis[Symbol.for('opentelemetry.js.api.1')]
console.log('registry.trace is a :', reg.trace.constructor.name)
console.log('registry.trace.getSpan :', typeof reg.trace.getSpan)
console.log('registry.trace.getTracer:', typeof reg.trace.getTracer)
console.log('registry.context is a :', reg.context.constructor.name)Output, on @opentelemetry/api 1.9.1:
registry.trace is a : ProxyTracerProvider
registry.trace.getSpan : undefined
registry.trace.getTracer: function
registry.context is a : AsyncLocalStorageContextManagerThere it is. registry.trace is a TracerProvider — the object that hands out tracers. It has getTracer. It has never had getSpan.
The trace you import from @opentelemetry/api is a different object entirely. It is a namespace with helper functions on it, and getSpan is one of those helpers. The two just happen to share a name.
You can see it in the API’s own source. When the SDK registers itself, it stores the provider, not the namespace:
const API_NAME = 'trace'
registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance())And registry.context is the context manager, which is the piece that really does have active(). That is why the first half of my function worked and the second half silently did not.
Because every step used optional chaining, getSpan?.() on an object with no getSpan is just undefined. No crash. No warning. span is undefined, so spanContext is undefined, so the function returns null — exactly as if no SDK were installed at all.
Here is the whole failure in one run, inside a real, live span:
real active span traceId : 16f5d4d39dc0f5c240e8b597a4e9b6f3
broken() returns : nullA real span was active. My code said there was nothing there.
The fix: ask the context for the span directly
If getSpan is a helper rather than something on the global, what does that helper actually do? In the OpenTelemetry source it is three lines:
const SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN')
function getSpan(context) {
return context.getValue(SPAN_KEY) || undefined
}A context is a small key-value bag. The span is just one value in it, stored under one key. And createContextKey is this:
function createContextKey(description) {
return Symbol.for(description)
}Symbol.for is the important part. A normal Symbol('x') is unique every time you call it, but Symbol.for('x') returns the same symbol for the same text, anywhere in the process. OpenTelemetry’s own comment explains why they chose it: “we use Symbol.for which returns the same key for the same input.” Two copies of the package at different versions still agree on the key.
Which means I can build that exact key myself, without importing anything:
const OTEL_API_KEY = Symbol.for('opentelemetry.js.api.1')
const SPAN_KEY = Symbol.for('OpenTelemetry Context Key SPAN')
const INVALID_TRACE_ID = '0'.repeat(32)
const INVALID_SPAN_ID = '0'.repeat(16)
export function getActiveSpanContext(): { traceId: string; spanId: string } | null {
try {
const registry = (globalThis as Record<symbol, unknown>)[OTEL_API_KEY] as
| { context?: { active?: () => unknown } }
| undefined
const active = registry?.context?.active?.() as
| { getValue?: (key: symbol) => unknown }
| undefined
if (!active || typeof active.getValue !== 'function') return null
const span = active.getValue(SPAN_KEY) as
| { spanContext?: () => { traceId?: unknown; spanId?: unknown } }
| undefined
const spanContext = span?.spanContext?.()
const traceId = spanContext?.traceId
const spanId = spanContext?.spanId
if (typeof traceId !== 'string' || typeof spanId !== 'string') return null
if (traceId === INVALID_TRACE_ID || spanId === INVALID_SPAN_ID) return null
return { traceId, spanId }
} catch {
return null
}
}Same run as before, with the fixed version added:
real active span traceId : 16f5d4d39dc0f5c240e8b597a4e9b6f3
broken() returns : null
fixed() returns : 16f5d4d39dc0f5c240e8b597a4e9b6f3
fixed matches real span : true
outside any span, fixed(): nullThis lookup runs on every single log call, so I measured it. On Node 22, two million calls per run, three runs:
WITH SDK, inside a span : 148.1 / 160.4 / 153.5 ns per call
NO SDK (returns null) : 21.3 / 21.2 / 20.4 ns per callRoughly 150 ns when there is a span to find, and about 21 ns when OpenTelemetry is not installed at all and the whole thing short-circuits on a missing global. For context, writing one line to stdout is on the order of microseconds, so this is noise next to the logging it is attached to.
It also follows nested spans correctly. If the app opens a span inside another span, the fixed version reports the inner one, which is the whole reason to prefer the active span over the header in the first place.
Be honest about what this is
This reads a key that OpenTelemetry treats as internal. It is not a documented public API, and a future major version could rename that string.
I still think it is the right call for a logging library, with two conditions. The try/catch and the type checks have to stay, so a changed shape produces a missing field and never a crash. And if you are writing an application rather than a library, do not do this at all — just import @opentelemetry/api and call trace.getSpan(context.active()). The whole argument for the global trick is avoiding a dependency you cannot justify forcing on your users. An app has no such problem.
The second bug, found by the same kind of check
While I was testing properly, I pointed the same suspicion at my traceparent parser. The regex was this:
/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/I had a comment next to it claiming it was forward-compatible: a future version 01 header would still work, instead of being thrown away.
Half true. A bare 01-... header does pass. But the W3C Trace Context spec is specific about what a future version looks like: new versions are additive, meaning they append extra fields on the end. The spec tells parsers to read the flags and accept either the end of the string or another dash after them.
My $ sits immediately after the flags. A dash there fails the match:
v01 bare -> parses
v01 with extra field -> nullSo the comment described the opposite of what the code did. The fix is to allow a trailing section, and to allow it only above version 00, since version 00 genuinely has no extra fields:
const TRACEPARENT_RE =
/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/
export function parseTraceparent(header: string | null | undefined) {
if (!header) return null
const match = TRACEPARENT_RE.exec(header.trim().toLowerCase())
if (!match) return null
const [, version, traceId, spanId, flags, rest] = match
if (version === 'ff') return null // reserved as invalid
if (version === '00' && rest) return null // v00 has no extra fields
if (traceId === INVALID_TRACE_ID) return null // all zeros is invalid
if (spanId === INVALID_SPAN_ID) return null
return { traceId, spanId, sampled: (parseInt(flags, 16) & 0x01) === 1 }
}Twelve cases against it, all passing:
PASS v00 sampled -> 4bf92f35… sampled=true
PASS v00 not sampled -> 4bf92f35… sampled=false
PASS v00 with trailing junk -> null
PASS v01 bare -> 4bf92f35… sampled=true
PASS v01 with extra field -> 4bf92f35… sampled=true
PASS ff reserved -> null
PASS all-zero traceId -> null
PASS all-zero spanId -> null
PASS too short -> null
PASS uppercase hex -> 4bf92f35… sampled=true
PASS empty string -> null
PASS garbage -> nullOne note on that uppercase case. The spec says traceparent is lowercase hex, so a header with capitals is technically invalid. I lowercase the string before matching, which means I accept it anyway. That is a deliberate choice to be forgiving about input, not an accident — but it is a place where my parser is looser than the spec, and you should decide that for yourself rather than inherit it from me.
The part worth keeping
The two bugs are small. The thing that let both of them live for months is not.
A mock you wrote from your own assumption can only ever confirm your assumption. My test did not test my code against OpenTelemetry. It tested my code against my memory of OpenTelemetry, and my memory was wrong. A green check mark felt like proof and was decoration.
I am not saying throw out your mocks. Mocks are how you test the twenty failure paths without standing up a real server twenty times. But when you are duck-typing against somebody else’s object, the shape itself is the risky part, and that is the one thing a hand-written mock cannot check. One test that installs the real package and asserts on a real value is worth more than a dozen mocked ones.
The second tell is quieter: both bugs were places where a comment promised more than the code delivered. “Forward-compatible.” “Reads the active span.” Comments do not run. When a comment makes a factual claim about behaviour, that claim deserves a test that could fail, or it is just a wish written in the past tense.
Checking your own code
If you read OpenTelemetry’s global anywhere, this one-liner tells you immediately:
grep -rn "opentelemetry.js.api" --include=*.ts --include=*.js . | grep -v node_modulesFor anything it finds, the question is: does it call .getSpan on the trace slot? If yes, that code has been returning null the whole time.
And the fastest way to see the truth, for this or any global you are duck-typing, is the thing I should have done first:
console.log(Object.keys(reg), reg.trace.constructor.name)Four seconds. It would have saved me the whole bug.