Skip to content

Commit d9322e7

Browse files
committed
fixup! feat(core): Export a reusable function to add tracing headers
1 parent fb1e8a2 commit d9322e7

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

packages/core/src/fetch.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ export function getTracingHeadersForFetchRequest(
240240
}
241241

242242
return newHeaders;
243-
} else if (Array.isArray(originalHeaders)) {
243+
} else if (isHeadersInitTupleArray(originalHeaders)) {
244244
const newHeaders = [...originalHeaders];
245245

246246
if (!originalHeaders.find(header => header[0] === 'sentry-trace')) {
@@ -261,7 +261,7 @@ export function getTracingHeadersForFetchRequest(
261261
newHeaders.push(['baggage', baggage]);
262262
}
263263

264-
return newHeaders as PolymorphicRequestHeaders;
264+
return newHeaders;
265265
} else {
266266
const existingSentryTraceHeader = 'sentry-trace' in originalHeaders ? originalHeaders['sentry-trace'] : undefined;
267267
const existingTraceparentHeader = 'traceparent' in originalHeaders ? originalHeaders.traceparent : undefined;
@@ -327,6 +327,18 @@ function isHeaders(headers: unknown): headers is Headers {
327327
return typeof Headers !== 'undefined' && isInstanceOf(headers, Headers);
328328
}
329329

330+
/** `HeadersInit` array form: each entry is a [name, value] pair of strings. */
331+
function isHeadersInitTupleArray(headers: unknown): headers is [string, string][] {
332+
if (!Array.isArray(headers)) {
333+
return false;
334+
}
335+
336+
return headers.every(
337+
(item): item is [string, string] =>
338+
Array.isArray(item) && item.length === 2 && typeof item[0] === 'string' && typeof item[1] === 'string',
339+
)
340+
}
341+
330342
function getSpanStartOptions(
331343
url: string,
332344
method: string,

packages/core/test/lib/fetch.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,21 @@ describe('getTracingHeadersForFetchRequest', () => {
9292
['baggage', DEFAULT_BAGGAGE],
9393
]);
9494
});
95+
96+
it('treats array with non-tuple items as headers object', () => {
97+
const returnedHeaders = getTracingHeadersForFetchRequest('/api/test', {
98+
headers: ['not-a-tuple', 'also-not-a-tuple'],
99+
});
100+
101+
// Falls through to the else branch (headers object handling)
102+
// since the array items are not [string, string] tuples
103+
expect(returnedHeaders).toEqual({
104+
'0': 'not-a-tuple',
105+
'1': 'also-not-a-tuple',
106+
'sentry-trace': DEFAULT_SENTRY_TRACE,
107+
baggage: DEFAULT_BAGGAGE,
108+
});
109+
});
95110
});
96111

97112
describe('and 3rd party baggage header is set', () => {

0 commit comments

Comments
 (0)