Skip to content

fix(browser): Ensure pageload & navigation spans have correct data #16279

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 14, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ Sentry.init({
});

// Immediately navigate to a new page to abort the pageload
window.location.href = '#foo';
window.history.pushState({}, '', '/sub-page');
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ sentryTest(
expect(navigationTraceId).toBeDefined();
expect(pageloadTraceId).not.toEqual(navigationTraceId);

expect(pageloadRequest.transaction).toEqual('/index.html');
expect(navigationRequest.transaction).toEqual('/sub-page');

expect(pageloadRequest.contexts?.trace?.data).toMatchObject({
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.browser',
[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: 1,
Expand All @@ -54,5 +57,17 @@ sentryTest(
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'navigation',
['sentry.idle_span_finish_reason']: 'idleTimeout',
});
expect(pageloadRequest.request).toEqual({
headers: {
'User-Agent': expect.any(String),
},
url: 'http://sentry-test.io/index.html',
});
expect(navigationRequest.request).toEqual({
headers: {
'User-Agent': expect.any(String),
},
url: 'http://sentry-test.io/sub-page',
});
},
);
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ sentryTest('should create a navigation transaction on page navigation', async ({
expect(navigationTraceId).toBeDefined();
expect(pageloadTraceId).not.toEqual(navigationTraceId);

expect(pageloadRequest.transaction).toEqual('/index.html');
// Fragment is not in transaction name
expect(navigationRequest.transaction).toEqual('/index.html');

expect(pageloadRequest.contexts?.trace?.data).toMatchObject({
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.browser',
[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: 1,
Expand All @@ -45,6 +49,18 @@ sentryTest('should create a navigation transaction on page navigation', async ({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'navigation',
['sentry.idle_span_finish_reason']: 'idleTimeout',
});
expect(pageloadRequest.request).toEqual({
headers: {
'User-Agent': expect.any(String),
},
url: 'http://sentry-test.io/index.html',
});
expect(navigationRequest.request).toEqual({
headers: {
'User-Agent': expect.any(String),
},
url: 'http://sentry-test.io/index.html#foo',
});

const pageloadSpans = pageloadRequest.spans;
const navigationSpans = navigationRequest.spans;
Expand Down
22 changes: 22 additions & 0 deletions packages/browser/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
addExceptionTypeValue,
addNonEnumerableProperty,
captureException,
getLocationHref,
getOriginalFunction,
GLOBAL_OBJ,
markFunctionWrapped,
Expand Down Expand Up @@ -175,3 +176,24 @@ export function wrap<T extends WrappableFunction, NonFunction>(

return sentryWrapped;
}

/**
* Get HTTP request data from the current page.
*/
export function getHttpRequestData(): { url: string; headers: Record<string, string> } {
// grab as much info as exists and add it to the event
const url = getLocationHref();
const { referrer } = WINDOW.document || {};
const { userAgent } = WINDOW.navigator || {};

const headers = {
...(referrer && { Referer: referrer }),
...(userAgent && { 'User-Agent': userAgent }),
};
const request = {
url,
headers,
};

return request;
}
20 changes: 7 additions & 13 deletions packages/browser/src/integrations/httpcontext.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defineIntegration, getLocationHref } from '@sentry/core';
import { WINDOW } from '../helpers';
import { defineIntegration } from '@sentry/core';
import { getHttpRequestData, WINDOW } from '../helpers';

/**
* Collects information about HTTP request headers and
Expand All @@ -14,23 +14,17 @@ export const httpContextIntegration = defineIntegration(() => {
return;
}

// grab as much info as exists and add it to the event
const url = event.request?.url || getLocationHref();
const { referrer } = WINDOW.document || {};
const { userAgent } = WINDOW.navigator || {};

const reqData = getHttpRequestData();
const headers = {
...reqData.headers,
...event.request?.headers,
...(referrer && { Referer: referrer }),
...(userAgent && { 'User-Agent': userAgent }),
};
const request = {

event.request = {
...reqData,
...event.request,
...(url && { url }),
headers,
};

event.request = request;
},
};
});
20 changes: 16 additions & 4 deletions packages/browser/src/tracing/browserTracingIntegration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import {
startTrackingWebVitals,
} from '@sentry-internal/browser-utils';
import { DEBUG_BUILD } from '../debug-build';
import { WINDOW } from '../helpers';
import { getHttpRequestData, WINDOW } from '../helpers';
import { registerBackgroundTabDetection } from './backgroundtab';
import { linkTraces } from './linkedTraces';
import { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';
Expand Down Expand Up @@ -355,11 +355,21 @@ export const browserTracingIntegration = ((_options: Partial<BrowserTracingOptio
sampled: spanIsSampled(idleSpan),
dsc: getDynamicSamplingContextFromSpan(span),
});

scope.setSDKProcessingMetadata({
normalizedRequest: undefined,
});
},
});

setActiveIdleSpan(client, idleSpan);

// We store the normalized request data on the scope, so we get the request data at time of span creation
// otherwise, the URL etc. may already be of the following navigation, and we'd report the wrong URL
getCurrentScope().setSDKProcessingMetadata({
normalizedRequest: getHttpRequestData(),
});

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m/q: maybe I'm missing some timing information but isn't there a good chance that setting the normalizedRequest to undefined in 360 applies to the same scope where we previously set it (370)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

argh, actually that does not work I just noticed, it fixed one test but broke another one - as this resets the request before we even process the transaction 😬 need to do this in a different way... basically the problem was apparent in some e2e tests. I think it becomes problematic in certain cases, e.g. nextjs pages router, where routing instrumentation triggers navigation spans before the url is updated 🤔

function emitFinish(): void {
if (optionalWindowDocument && ['interactive', 'complete'].includes(optionalWindowDocument.readyState)) {
client.emit('idleSpanEnableAutoFinish', idleSpan);
Expand Down Expand Up @@ -459,16 +469,18 @@ export const browserTracingIntegration = ((_options: Partial<BrowserTracingOptio
return;
}

if (from !== to) {
startingUrl = undefined;
startingUrl = undefined;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m/q: why did we remove the from !== to check?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry, forgot to mention this - we actually have the same check in the history handler code, where we do not even trigger the handler in this case!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice, good catch!


// We wait a tick here to ensure that WINDOW.location.pathname is updated
setTimeout(() => {
Copy link
Member

@Lms24 Lms24 May 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m: I'm a bit worried about delaying the span start for a tick. I guess this comes down to the router or user implementation but what if users synchronously push a new state and e.g. make a fetch call directly afterwards? Would we still catch the span?
i think alternatively, we could still start the span directly but call updateSpanName once more in the setTimeout closure.
Not ideal in terms of DSC consistency but I'd rather have the span than miss it. WDYT?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm, valid. one thing that would work as expected is if we just would use the to attribute from the history API, this is available already. I was afraid to do that because 🤷 if that is consistent with what we want/need there...?

startBrowserTracingNavigationSpan(client, {
name: WINDOW.location.pathname,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.browser',
},
});
}
});
});
}
}
Expand Down
13 changes: 11 additions & 2 deletions packages/browser/test/tracing/browserTracingIntegration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ describe('browserTracingIntegration', () => {
expect(spanIsSampled(span!)).toBe(false);
});

it('starts navigation when URL changes', () => {
it('starts navigation when URL changes', async () => {
const client = new BrowserClient(
getDefaultBrowserClientOptions({
tracesSampleRate: 1,
Expand Down Expand Up @@ -187,6 +187,9 @@ describe('browserTracingIntegration', () => {

WINDOW.history.pushState({}, '', '/test');

// wait a tick to ensure everything settled
await new Promise(resolve => setTimeout(resolve, 1));

expect(span!.isRecording()).toBe(false);

const span2 = getActiveSpan();
Expand Down Expand Up @@ -225,6 +228,9 @@ describe('browserTracingIntegration', () => {

WINDOW.history.pushState({}, '', '/test2');

// wait a tick to ensure everything settled
await new Promise(resolve => setTimeout(resolve, 1));

expect(span2!.isRecording()).toBe(false);

const span3 = getActiveSpan();
Expand Down Expand Up @@ -861,7 +867,7 @@ describe('browserTracingIntegration', () => {
expect(propagationContext.parentSpanId).toEqual('1121201211212012');
});

it('ignores the meta tag data for navigation spans', () => {
it('ignores the meta tag data for navigation spans', async () => {
document.head.innerHTML =
'<meta name="sentry-trace" content="12312012123120121231201212312012-1121201211212012-0">' +
'<meta name="baggage" content="sentry-release=2.1.14">';
Expand All @@ -883,6 +889,9 @@ describe('browserTracingIntegration', () => {

WINDOW.history.pushState({}, '', '/navigation-test');

// wait a tick to ensure everything settled
await new Promise(resolve => setTimeout(resolve, 1));

const idleSpan = getActiveSpan()!;
expect(idleSpan).toBeDefined();

Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/tracing/sentrySpan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,8 @@ export class SentrySpan implements Span {

const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);

const normalizedRequest = capturedSpanScope?.getScopeData().sdkProcessingMetadata?.normalizedRequest;

if (this._sampled !== true) {
return undefined;
}
Expand Down Expand Up @@ -374,6 +376,7 @@ export class SentrySpan implements Span {
capturedSpanIsolationScope,
dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),
},
request: normalizedRequest,
...(source && {
transaction_info: {
source,
Expand Down
Loading