Skip to content

Commit f46ce6b

Browse files
committed
fix(nextjs): Start a waiting pageload before the navigation span
`browserTracingIntegration` registers its `startNavigationSpan` handler in `setup`, before the Next.js handler in `afterAllSetup`. A navigation during the wait therefore created its span first, and the late pageload ended it. Settling on `beforeStartNavigationSpan` does not depend on that order.
1 parent 7a4cf16 commit f46ce6b

4 files changed

Lines changed: 118 additions & 5 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { headers } from 'next/headers';
2+
import Link from 'next/link';
3+
import { Suspense } from 'react';
4+
5+
// The dynamic part, and with it the trace meta tag, streams in seconds after the shell, so a test
6+
// can navigate while the pageload still waits for the tag.
7+
async function SlowContent() {
8+
await headers();
9+
await new Promise(resolve => setTimeout(resolve, 4000));
10+
return <p id="slow-content">Slow content</p>;
11+
}
12+
13+
export default function Page() {
14+
return (
15+
<>
16+
<Link id="navigate" href="/static-shell">
17+
Static shell
18+
</Link>
19+
<Suspense fallback={<p id="slow-fallback">Loading...</p>}>
20+
<SlowContent />
21+
</Suspense>
22+
</>
23+
);
24+
}

‎dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/tests/cacheOrigin-pageloadConnection.spec.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,34 @@ test('starts a fresh trace on a fully static page', async ({ page }) => {
105105
expect(pageloadSpan.trace_id).toBeTruthy();
106106
expect(pageloadSpan.links).toBeUndefined();
107107
});
108+
109+
test('keeps a navigation that starts while the pageload waits for the trace meta tag', async ({ page }) => {
110+
test.skip(process.env.TEST_ENV !== 'production', 'Only a prerendered shell makes the trace meta tag arrive late');
111+
112+
const pageloadSpanPromise = waitForStreamedSpan(APP, span => {
113+
return span.name === '/slow-hole' && getSpanOp(span) === 'pageload' && span.is_segment;
114+
});
115+
116+
const navigationSpanPromise = waitForStreamedSpan(APP, span => {
117+
return span.name === '/static-shell' && getSpanOp(span) === 'navigation' && span.is_segment;
118+
});
119+
120+
await page.goto('/slow-hole', { waitUntil: 'commit' });
121+
await page.waitForFunction(() => !!(window as { next?: { router?: unknown } }).next?.router);
122+
123+
// The resumed part, which carries the tag, has not arrived yet, so the pageload is still waiting.
124+
await expect(page.locator('#slow-fallback')).toBeVisible();
125+
expect(await page.locator('meta[name="sentry-trace"]').count()).toBe(0);
126+
127+
await page.locator('#navigate').click();
128+
await expect(page.locator('#static-shell')).toHaveText('Static shell');
129+
130+
const [pageloadSpan, navigationSpan] = await Promise.all([pageloadSpanPromise, navigationSpanPromise]);
131+
132+
// The navigation ends the pageload like any pageload it interrupts, and runs to its own idle timeout.
133+
expect(pageloadSpan.attributes['sentry.idle_span_finish_reason']).toEqual({ type: 'string', value: 'cancelled' });
134+
expect(navigationSpan.attributes['sentry.idle_span_finish_reason']).toEqual({
135+
type: 'string',
136+
value: 'idleTimeout',
137+
});
138+
});

‎packages/nextjs/src/client/browserTracingIntegration.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,11 @@ export function browserTracingIntegration(
4242
nextRouterInstrumentNavigation(client);
4343
}
4444

45-
// Registered before the browser tracing integration's own handler, which creates the navigation
46-
// span: a pageload that is still waiting for its trace meta tag has to exist by then, so the
47-
// handler ends it like any pageload a navigation interrupts. Started later, the pageload would
48-
// end the navigation span instead.
45+
// A pageload that is still waiting for its trace meta tag has to exist before the navigation span,
46+
// so the navigation ends it like any pageload it interrupts. Started later, the pageload would end
47+
// the navigation span instead.
4948
if (instrumentPageLoad) {
50-
client.on('startNavigationSpan', settlePendingPageloadWait);
49+
client.on('beforeStartNavigationSpan', settlePendingPageloadWait);
5150
}
5251

5352
browserTracingIntegrationInstance.afterAllSetup(client);
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// @vitest-environment jsdom
2+
import { SENTRY_OP } from '@sentry/conventions/attributes';
3+
import { NAVIGATION, PAGELOAD } from '@sentry/conventions/op';
4+
import type { Span } from '@sentry/core';
5+
import {
6+
createTransport,
7+
getActiveSpan,
8+
getCurrentScope,
9+
resolvedSyncPromise,
10+
setCurrentClient,
11+
spanToJSON,
12+
} from '@sentry/core';
13+
import { BrowserClient, startBrowserTracingNavigationSpan } from '@sentry/react';
14+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
15+
import { browserTracingIntegration } from '../../src/client/browserTracingIntegration';
16+
17+
describe('browserTracingIntegration', () => {
18+
const originalReadyState = Object.getOwnPropertyDescriptor(Document.prototype, 'readyState');
19+
20+
beforeEach(() => {
21+
window.history.replaceState({}, '', '/products');
22+
Object.defineProperty(document, 'readyState', { value: 'loading', configurable: true });
23+
vi.spyOn(performance, 'getEntriesByType').mockReturnValue([]);
24+
vi.stubEnv('_sentryCacheComponents', 'true');
25+
});
26+
27+
afterEach(() => {
28+
getCurrentScope().setClient(undefined);
29+
// @ts-expect-error deleting the instance override restores the prototype getter
30+
delete document.readyState;
31+
if (originalReadyState) {
32+
Object.defineProperty(Document.prototype, 'readyState', originalReadyState);
33+
}
34+
vi.restoreAllMocks();
35+
vi.unstubAllEnvs();
36+
});
37+
38+
it('ends a pageload that waits for its trace meta tag when a navigation starts, and keeps the navigation', () => {
39+
const client = new BrowserClient({
40+
dsn: 'http://examplePublicKey@localhost/0',
41+
transport: () => createTransport({ recordDroppedEvent: () => undefined }, () => resolvedSyncPromise({})),
42+
stackParser: () => [],
43+
tracesSampleRate: 1,
44+
integrations: [browserTracingIntegration({ instrumentNavigation: false })],
45+
});
46+
const endedSpans: Span[] = [];
47+
client.on('spanEnd', span => endedSpans.push(span));
48+
setCurrentClient(client);
49+
client.init();
50+
51+
const navigationSpan = startBrowserTracingNavigationSpan(client, { name: '/products/42' });
52+
53+
expect(endedSpans).toHaveLength(1);
54+
expect(spanToJSON(endedSpans[0]!).attributes?.[SENTRY_OP]).toBe(PAGELOAD);
55+
expect(getActiveSpan()).toBe(navigationSpan);
56+
expect(navigationSpan!.isRecording()).toBe(true);
57+
expect(spanToJSON(navigationSpan!).attributes?.[SENTRY_OP]).toBe(NAVIGATION);
58+
});
59+
});

0 commit comments

Comments
 (0)