1- /* eslint-disable max-lines */
21import type * as http from 'node:http' ;
32import type { IncomingMessage , RequestOptions } from 'node:http' ;
43import type * as https from 'node:https' ;
54import type { EventEmitter } from 'node:stream' ;
5+ /* eslint-disable max-lines */
66import { VERSION } from '@opentelemetry/core' ;
77import type { InstrumentationConfig } from '@opentelemetry/instrumentation' ;
88import { InstrumentationBase , InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation' ;
9- import type { AggregationCounts , Client , RequestEventData , SanitizedRequestData , Scope } from '@sentry/core' ;
9+ import type {
10+ AggregationCounts ,
11+ Client ,
12+ RequestEventData ,
13+ SanitizedRequestData ,
14+ Scope } from '@sentry/core' ;
1015import {
1116 LRUMap ,
1217 addBreadcrumb ,
@@ -18,6 +23,8 @@ import {
1823 getTraceData ,
1924 httpRequestToRequestData ,
2025 logger ,
26+ objectToBaggageHeader ,
27+ parseBaggageHeader ,
2128 parseUrl ,
2229 stripUrlQueryAndFragment ,
2330 withIsolationScope ,
@@ -493,14 +500,17 @@ function addSentryHeadersToRequestOptions(
493500 }
494501 const headers = options . headers ;
495502
496- Object . entries ( addedHeaders ) . forEach ( ( [ k , v ] ) => {
497- // We do not want to overwrite existing headers here
498- // If the core HttpInstrumentation is registered, it will already have set the headers
499- // We do not want to add any then
500- if ( ! headers [ k ] ) {
501- headers [ k ] = v ;
502- }
503- } ) ;
503+ const { 'sentry-trace' : sentryTrace , baggage } = addedHeaders ;
504+
505+ // We do not want to overwrite existing header here, if it was already set
506+ if ( sentryTrace && ! headers [ 'sentry-trace' ] ) {
507+ headers [ 'sentry-trace' ] = sentryTrace ;
508+ }
509+
510+ // For baggage, we make sure to merge this into a possibly existing header
511+ if ( baggage ) {
512+ headers [ 'baggage' ] = mergeBaggageHeaders ( headers [ 'baggage' ] , baggage ) ;
513+ }
504514}
505515
506516/**
@@ -597,3 +607,20 @@ function getAbsoluteUrl(origin: string, path: string = '/'): string {
597607 return `${ url } ${ path } ` ;
598608 }
599609}
610+
611+ function mergeBaggageHeaders (
612+ existing : string | string [ ] | number | null | undefined | boolean ,
613+ baggage : string ,
614+ ) : string | undefined {
615+ if ( ! existing ) {
616+ return baggage ;
617+ }
618+
619+ const existingBaggageEntries = parseBaggageHeader ( existing ) ;
620+ const newBaggageEntries = parseBaggageHeader ( baggage ) ;
621+
622+ // Existing entries take precedence
623+ const mergedBaggageEntries = { ...newBaggageEntries , ...existingBaggageEntries } ;
624+
625+ return objectToBaggageHeader ( mergedBaggageEntries ) ;
626+ }
0 commit comments