Skip to content

Commit f44d6a7

Browse files
committed
fix(node): Avoid setting sentry-trace header multiple times
If, for whatever reason, `propagator.inject()` is called multiple times, we do not want to add multiple `sentry-trace` headers. In this case, the first one wins.
1 parent 668c276 commit f44d6a7

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

packages/opentelemetry/src/propagator.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,9 @@ export class SentryPropagator extends W3CBaggagePropagator {
8787
}
8888

8989
// We also want to avoid setting the default OTEL trace ID, if we get that for whatever reason
90-
if (traceId && traceId !== INVALID_TRACEID) {
90+
// If a sentry-trace header already exists, we do nothing
91+
const existingSentryTrace = getExistingSentryTrace(carrier);
92+
if (traceId && traceId !== INVALID_TRACEID && !existingSentryTrace) {
9193
setter.set(carrier, SENTRY_TRACE_HEADER, generateSentryTraceHeader(traceId, spanId, sampled));
9294
}
9395

@@ -264,6 +266,16 @@ function getExistingBaggage(carrier: unknown): string | undefined {
264266
}
265267
}
266268

269+
/** Try to get the existing sentry-trace header. */
270+
function getExistingSentryTrace(carrier: unknown): string | undefined {
271+
try {
272+
const sentryTrace = (carrier as Record<string, string | string[]>)[SENTRY_TRACE_HEADER];
273+
return Array.isArray(sentryTrace) ? sentryTrace.join(',') : sentryTrace;
274+
} catch {
275+
return undefined;
276+
}
277+
}
278+
267279
/**
268280
* It is pretty tricky to get access to the outgoing request URL of a request in the propagator.
269281
* As we only have access to the context of the span to be sent and the carrier (=headers),

0 commit comments

Comments
 (0)