Skip to content

Commit 531fb38

Browse files
committed
Allow fetch to be used with NodeJS native fetch
1 parent c320c98 commit 531fb38

File tree

2 files changed

+13
-3
lines changed
  • experimental/packages/opentelemetry-instrumentation-fetch/src
  • packages/opentelemetry-sdk-trace-web/src

2 files changed

+13
-3
lines changed

experimental/packages/opentelemetry-instrumentation-fetch/src/fetch.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,12 @@ export class FetchInstrumentation extends InstrumentationBase<
132132
SemanticAttributes.HTTP_SCHEME,
133133
parsedUrl.protocol.replace(':', '')
134134
);
135-
span.setAttribute(SemanticAttributes.HTTP_USER_AGENT, navigator.userAgent);
135+
if (typeof navigator !== 'undefined') {
136+
span.setAttribute(
137+
SemanticAttributes.HTTP_USER_AGENT,
138+
navigator.userAgent
139+
);
140+
}
136141
}
137142

138143
/**

packages/opentelemetry-sdk-trace-web/src/utils.ts

+7-2
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,11 @@ export function sortResources(
131131
});
132132
}
133133

134+
/** Returns the origin if present (if in browser context). */
135+
function getOrigin(): string | undefined {
136+
return typeof location !== 'undefined' ? location.origin : undefined;
137+
}
138+
134139
/**
135140
* Get closest performance resource ignoring the resources that have been
136141
* already used.
@@ -174,7 +179,7 @@ export function getResource(
174179
}
175180
const sorted = sortResources(filteredResources);
176181

177-
if (parsedSpanUrl.origin !== location.origin && sorted.length > 1) {
182+
if (parsedSpanUrl.origin !== getOrigin() && sorted.length > 1) {
178183
let corsPreFlightRequest: PerformanceResourceTiming | undefined = sorted[0];
179184
let mainRequest: PerformanceResourceTiming = findMainRequest(
180185
sorted,
@@ -438,7 +443,7 @@ export function shouldPropagateTraceHeaders(
438443
}
439444
const parsedSpanUrl = parseUrl(spanUrl);
440445

441-
if (parsedSpanUrl.origin === location.origin) {
446+
if (parsedSpanUrl.origin === getOrigin()) {
442447
return true;
443448
} else {
444449
return propagateTraceHeaderUrls.some(propagateTraceHeaderUrl =>

0 commit comments

Comments
 (0)