From 3f53d90fa1461c57b3f6236b692a222a2a63e13f Mon Sep 17 00:00:00 2001 From: Charly Gomez Date: Thu, 26 Nov 2026 13:06:07 +0100 Subject: [PATCH 1/6] feat(nextjs): Continue injected trace meta tags in Pages Router pageloads A mobile SDK can inject `sentry-trace` and `baggage` meta tags into the document of a WebView. The Pages Router pageload ignored them and continued the server trace. It now continues a meta tag that belongs to another trace than the server request, and keeps the previous behavior in every other case. Co-Authored-By: Claude Fable 5.2 --- .../injected-trace-meta-tags.test.ts | 51 ++++++++ .../tests/pages-router.test.ts | 35 ++++++ .../pagesRouterRoutingInstrumentation.ts | 47 ++++++- .../src/client/routing/traceMetaTags.ts | 17 ++- .../pagesRouterInstrumentation.test.ts | 115 +++++++++++++++++- 5 files changed, 258 insertions(+), 7 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts new file mode 100644 index 000000000000..ea8f368d5c7d --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts @@ -0,0 +1,51 @@ +import { expect, test } from '@playwright/test'; +import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { parseSemver } from '@sentry/core'; + +const nextPackageJson = require('next/package.json'); +const nextjsVersion = nextPackageJson.version; +const { major, minor } = parseSemver(nextjsVersion); + +const INJECTED_TRACE_ID = '12345678901234567890123456789012'; +const INJECTED_PARENT_SPAN_ID = '1234567890123456'; + +test('Should continue the trace of injected meta tags instead of the server trace in pages router', async ({ + page, +}) => { + test.skip( + major === 15 && minor !== undefined && minor < 3, + 'Next.js version does not support clientside instrumentation', + ); + + // Stands in for a mobile SDK that injects the tags into the document of a WebView. + await page.route('**/123/pages-router-client-trace-propagation', async route => { + const response = await route.fetch(); + const html = await response.text(); + const metaTags = + `` + + ``; + // After the tags Next.js renders for the request, so the order of the tags cannot decide the outcome. + await route.fulfill({ response, body: html.replace('', `${metaTags}`) }); + }); + + const serverSpanPromise = waitForStreamedSpan('nextjs-15', span => { + return span.name === 'GET /[locale]/pages-router-client-trace-propagation' && span.is_segment; + }); + + const pageloadSpanPromise = waitForStreamedSpan('nextjs-15', span => { + return ( + span.name === '/[locale]/pages-router-client-trace-propagation' && + getSpanOp(span) === 'pageload' && + span.is_segment + ); + }); + + await page.goto(`/123/pages-router-client-trace-propagation`); + + const serverSpan = await serverSpanPromise; + const pageloadSpan = await pageloadSpanPromise; + + expect(serverSpan.trace_id).not.toBe(INJECTED_TRACE_ID); + expect(pageloadSpan.trace_id).toBe(INJECTED_TRACE_ID); + expect(pageloadSpan.parent_span_id).toBe(INJECTED_PARENT_SPAN_ID); +}); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts index f9d268ada785..85b146552185 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts @@ -21,3 +21,38 @@ test('continues the server trace in the pageload of a Pages Router page', async expect(pageloadSpan.trace_id).toBe(serverSpan.trace_id); expect(pageloadSpan.attributes[SENTRY_ORIGIN]?.value).toBe('auto.pageload.nextjs.pages_router_instrumentation'); }); + +const INJECTED_TRACE_ID = '12345678901234567890123456789012'; +const INJECTED_PARENT_SPAN_ID = '1234567890123456'; + +test('continues the trace of injected meta tags instead of the server trace in a Pages Router page', async ({ + page, +}) => { + // Stands in for a mobile SDK that injects the tags into the document of a WebView. + await page.route('**/pages-router-ssr', async route => { + const response = await route.fetch(); + const html = await response.text(); + const metaTags = + `` + + ``; + // After the tags Next.js renders for the request, so the order of the tags cannot decide the outcome. + await route.fulfill({ response, body: html.replace('', `${metaTags}`) }); + }); + + const serverSpanPromise = waitForStreamedSpan('nextjs-16-standalone', span => { + return span.name === 'GET /pages-router-ssr' && getSpanOp(span) === HTTP_SERVER && span.is_segment; + }); + + const pageloadSpanPromise = waitForStreamedSpan('nextjs-16-standalone', span => { + return span.name === '/pages-router-ssr' && getSpanOp(span) === PAGELOAD && span.is_segment; + }); + + await page.goto('/pages-router-ssr'); + + const serverSpan = await serverSpanPromise; + const pageloadSpan = await pageloadSpanPromise; + + expect(serverSpan.trace_id).not.toBe(INJECTED_TRACE_ID); + expect(pageloadSpan.trace_id).toBe(INJECTED_TRACE_ID); + expect(pageloadSpan.parent_span_id).toBe(INJECTED_PARENT_SPAN_ID); +}); diff --git a/packages/nextjs/src/client/routing/pagesRouterRoutingInstrumentation.ts b/packages/nextjs/src/client/routing/pagesRouterRoutingInstrumentation.ts index c37599e69fcb..527dde5fa347 100644 --- a/packages/nextjs/src/client/routing/pagesRouterRoutingInstrumentation.ts +++ b/packages/nextjs/src/client/routing/pagesRouterRoutingInstrumentation.ts @@ -1,11 +1,18 @@ import type { Client } from '@sentry/core'; -import { debug, hasSpanStreamingEnabled, PAGELOAD_SPAN_NAME_FALLBACK, parseBaggageHeader } from '@sentry/core'; +import { + debug, + extractTraceparentData, + hasSpanStreamingEnabled, + PAGELOAD_SPAN_NAME_FALLBACK, + parseBaggageHeader, +} from '@sentry/core'; import { startBrowserTracingPageLoadSpan, WINDOW } from '@sentry/react'; import type { NEXT_DATA } from 'next/dist/shared/lib/utils'; import type { ParsedUrlQuery } from 'querystring'; import { DEBUG_BUILD } from '../../common/debug-build'; import { SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE, URL_TEMPLATE, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import { PAGELOAD } from '@sentry/conventions/op'; +import { getServerTimingSentryTrace } from './traceMetaTags'; const globalObject = WINDOW; @@ -113,10 +120,46 @@ export function pagesRouterInstrumentPageLoad(client: Client): void { ...(params && { ...params }), }, }, - { sentryTrace, baggage }, + // Turbopack does not wrap data fetchers, so `__NEXT_DATA__` has no trace and the header has to tell the tags apart. + getForeignTraceMetaTags(sentryTrace || getServerTimingSentryTrace()) ?? { sentryTrace, baggage }, ); } +/** + * Finds `sentry-trace` and `baggage` meta tags that belong to another trace than the one of the server + * request. Next.js renders the trace of the request into the same kind of tags, so a + * tag is only known to come from somewhere else, e.g. from a mobile SDK that wants its WebView to + * continue the trace of the app, when its trace ID differs. + */ +function getForeignTraceMetaTags( + serverSentryTrace: string | undefined, +): { sentryTrace: string; baggage: string } | undefined { + const serverTraceId = extractTraceparentData(serverSentryTrace)?.traceId; + if (!serverTraceId) { + return undefined; + } + + const metaContents = (name: string): string[] => + Array.from(globalObject.document.querySelectorAll(`meta[name="${name}"]`)) + .map(tag => tag.getAttribute('content')) + .filter((content): content is string => !!content); + + for (const sentryTrace of metaContents('sentry-trace')) { + const traceId = extractTraceparentData(sentryTrace)?.traceId; + // Without a baggage of its own, the browser SDK would fall back to the first `baggage` tag of the + // document, which can be the one of the server trace, and combine two traces. + const baggage = + traceId && traceId !== serverTraceId + ? metaContents('baggage').find(value => parseBaggageHeader(value)?.['sentry-trace_id'] === traceId) + : undefined; + if (baggage) { + return { sentryTrace, baggage }; + } + } + + return undefined; +} + /** * Matches a pathname against the Pages Router build manifest, e.g. `/users/1` -> `/users/[id]`. * diff --git a/packages/nextjs/src/client/routing/traceMetaTags.ts b/packages/nextjs/src/client/routing/traceMetaTags.ts index d17a67fc877d..25fb35e68c42 100644 --- a/packages/nextjs/src/client/routing/traceMetaTags.ts +++ b/packages/nextjs/src/client/routing/traceMetaTags.ts @@ -40,15 +40,24 @@ export function readTraceMetaTags(): TraceMetaTagValues | undefined { return document && sentryTrace ? { sentryTrace, baggage: lastMetaContent(document, 'baggage') } : undefined; } +function getServerTimingEntry(name: string): PerformanceServerTiming | undefined { + // The cast is required for the declaration build, which resolves `getEntriesByType('navigation')` + // to `PerformanceEntry[]` without `serverTiming`. + const navigation = WINDOW.performance?.getEntriesByType?.('navigation')[0] as PerformanceNavigationTiming | undefined; + return navigation?.serverTiming?.find(entry => entry.name === name); +} + /** * Whether the response carried the trace in a `Server-Timing` header. The generic browser tracing * integration continues it when it starts the pageload, so there is nothing to wait for. */ export function hasServerTimingTraceContext(): boolean { - // The cast is required for the declaration build, which resolves `getEntriesByType('navigation')` - // to `PerformanceEntry[]` without `serverTiming`. - const navigation = WINDOW.performance?.getEntriesByType?.('navigation')[0] as PerformanceNavigationTiming | undefined; - return !!navigation?.serverTiming?.some(entry => entry.name === 'sentry-trace'); + return !!getServerTimingEntry('sentry-trace'); +} + +/** The `sentry-trace` value of the `Server-Timing` header of the document, which a self-hosted server sends. */ +export function getServerTimingSentryTrace(): string | undefined { + return getServerTimingEntry('sentry-trace')?.description || undefined; } /** diff --git a/packages/nextjs/test/performance/pagesRouterInstrumentation.test.ts b/packages/nextjs/test/performance/pagesRouterInstrumentation.test.ts index fb7dc10c3019..c393914439f6 100644 --- a/packages/nextjs/test/performance/pagesRouterInstrumentation.test.ts +++ b/packages/nextjs/test/performance/pagesRouterInstrumentation.test.ts @@ -58,6 +58,7 @@ describe('pagesRouterInstrumentPageLoad', () => { props?: any; navigatableRoutes?: string[]; hasNextData: boolean; + head?: string; }) { const nextDataContent: NEXT_DATA = { props: pageProperties.props, @@ -73,7 +74,7 @@ describe('pagesRouterInstrumentPageLoad', () => { const dom = new JSDOM( // Just an example of what a __NEXT_DATA__ tag might look like pageProperties.hasNextData - ? `` + ? `${pageProperties.head ?? ''}` : '

No next data :(

', { url: pageProperties.url }, ); @@ -213,6 +214,118 @@ describe('pagesRouterInstrumentPageLoad', () => { ); }, ); + + describe('with trace meta tags in the document', () => { + const SERVER_TRACE_ID = 'c82b8554881b4d28ad977de04a4fb40a'; + const FOREIGN_TRACE_ID = '12345678901234567890123456789012'; + const nextDataTrace = { + sentryTrace: `${SERVER_TRACE_ID}-a755953cd3394d5f-1`, + baggage: `sentry-trace_id=${SERVER_TRACE_ID},sentry-release=2.1.0,sentry-environment=myEnv`, + }; + // Next.js renders these for the request, with the span that was active while the document rendered. + const serverMetaTags = ``; + const foreignTrace = { + sentryTrace: `${FOREIGN_TRACE_ID}-1234567890123456-1`, + baggage: `sentry-trace_id=${FOREIGN_TRACE_ID},sentry-release=mobile`, + }; + const foreignMetaTags = ``; + + function instrumentPageLoad( + head: string, + pageProps: Record = { + _sentryTraceData: nextDataTrace.sentryTrace, + _sentryBaggage: nextDataTrace.baggage, + }, + route = '/some-page', + ): ReturnType { + setUpNextPage({ url: 'https://example.com/some-page', route, props: { pageProps }, hasNextData: true, head }); + const emit = vi.fn(); + pagesRouterInstrumentPageLoad({ emit, getOptions: () => ({}) } as unknown as Client); + return emit; + } + + it.each([ + ['before the meta tags of the server', `${foreignMetaTags}${serverMetaTags}`], + ['after the meta tags of the server', `${serverMetaTags}${foreignMetaTags}`], + ['without meta tags of the server', foreignMetaTags], + ])('continues the trace of meta tags that belong to another trace, %s', (_, head) => { + const emit = instrumentPageLoad(head); + + expect(emit).toHaveBeenCalledTimes(1); + expect(emit).toHaveBeenCalledWith( + 'startPageLoadSpan', + expect.objectContaining({ name: '/some-page' }), + foreignTrace, + ); + }); + + it.each([ + ['the meta tags of the server', serverMetaTags], + ['an empty `sentry-trace` meta tag', ''], + ['a `sentry-trace` meta tag without content', ''], + ['an invalid `sentry-trace` meta tag', ''], + [ + 'a `sentry-trace` meta tag of another trace without its baggage', + `${serverMetaTags}`, + ], + ['only a `baggage` meta tag of another trace', ``], + ['unrelated meta tags', ''], + ])('keeps the `__NEXT_DATA__` trace with %s', (_, head) => { + const emit = instrumentPageLoad(head); + + expect(emit).toHaveBeenCalledWith('startPageLoadSpan', expect.anything(), nextDataTrace); + }); + + describe('when `__NEXT_DATA__` has no trace', () => { + const noTrace = { sentryTrace: undefined, baggage: undefined }; + + function setServerTimingTrace(sentryTrace: string): void { + vi.spyOn(performance, 'getEntriesByType').mockReturnValue([ + { + serverTiming: [{ name: 'sentry-trace', description: sentryTrace, duration: 0 }], + } as unknown as PerformanceEntry, + ]); + } + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('continues the trace of meta tags that belong to another trace than the `Server-Timing` header', () => { + setServerTimingTrace(nextDataTrace.sentryTrace); + const emit = instrumentPageLoad(`${serverMetaTags}${foreignMetaTags}`, {}); + + expect(emit).toHaveBeenCalledWith('startPageLoadSpan', expect.anything(), foreignTrace); + }); + + it('leaves the meta tags of the server to the browser SDK', () => { + setServerTimingTrace(nextDataTrace.sentryTrace); + const emit = instrumentPageLoad(serverMetaTags, {}); + + expect(emit).toHaveBeenCalledWith('startPageLoadSpan', expect.anything(), noTrace); + }); + + it('leaves the meta tags to the browser SDK without a `Server-Timing` header', () => { + const emit = instrumentPageLoad(`${serverMetaTags}${foreignMetaTags}`, {}); + + expect(emit).toHaveBeenCalledWith('startPageLoadSpan', expect.anything(), noTrace); + }); + }); + + it('still names an `/_error` pageload after the `__NEXT_DATA__` baggage', () => { + const emit = instrumentPageLoad( + foreignMetaTags, + { _sentryTraceData: nextDataTrace.sentryTrace, _sentryBaggage: 'sentry-transaction=GET /users/[id]' }, + '/_error', + ); + + expect(emit).toHaveBeenCalledWith( + 'startPageLoadSpan', + expect.objectContaining({ name: '/users/[id]' }), + foreignTrace, + ); + }); + }); }); describe('pagesRouterInstrumentNavigation', () => { From ea2421d6b6ad3979c3413b6bd240345d1b85dea8 Mon Sep 17 00:00:00 2001 From: Charly Gomez Date: Thu, 26 Nov 2026 13:39:31 +0100 Subject: [PATCH 2/6] test(nextjs): Read the server trace from the document in the injected meta tag tests Co-Authored-By: Claude Fable 5.2 --- .../injected-trace-meta-tags.test.ts | 17 ++++++++--------- .../tests/pages-router.test.ts | 12 ++++++------ 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts index ea8f368d5c7d..9b9c331ca692 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts @@ -1,4 +1,5 @@ import { expect, test } from '@playwright/test'; +import { PAGELOAD } from '@sentry/conventions/op'; import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; import { parseSemver } from '@sentry/core'; @@ -17,10 +18,13 @@ test('Should continue the trace of injected meta tags instead of the server trac 'Next.js version does not support clientside instrumentation', ); + let serverSentryTrace: string | undefined; + // Stands in for a mobile SDK that injects the tags into the document of a WebView. await page.route('**/123/pages-router-client-trace-propagation', async route => { const response = await route.fetch(); const html = await response.text(); + serverSentryTrace = html.match(/` + ``; @@ -28,24 +32,19 @@ test('Should continue the trace of injected meta tags instead of the server trac await route.fulfill({ response, body: html.replace('', `${metaTags}`) }); }); - const serverSpanPromise = waitForStreamedSpan('nextjs-15', span => { - return span.name === 'GET /[locale]/pages-router-client-trace-propagation' && span.is_segment; - }); - const pageloadSpanPromise = waitForStreamedSpan('nextjs-15', span => { return ( - span.name === '/[locale]/pages-router-client-trace-propagation' && - getSpanOp(span) === 'pageload' && - span.is_segment + span.name === '/[locale]/pages-router-client-trace-propagation' && getSpanOp(span) === PAGELOAD && span.is_segment ); }); await page.goto(`/123/pages-router-client-trace-propagation`); - const serverSpan = await serverSpanPromise; const pageloadSpan = await pageloadSpanPromise; - expect(serverSpan.trace_id).not.toBe(INJECTED_TRACE_ID); + // The document also carries the tags Next.js rendered for the request, which belong to the server trace. + expect(serverSentryTrace).toMatch(/^[0-9a-f]{32}-[0-9a-f]{16}/); + expect(serverSentryTrace).not.toContain(INJECTED_TRACE_ID); expect(pageloadSpan.trace_id).toBe(INJECTED_TRACE_ID); expect(pageloadSpan.parent_span_id).toBe(INJECTED_PARENT_SPAN_ID); }); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts index 85b146552185..5f69828bf88f 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts @@ -28,10 +28,13 @@ const INJECTED_PARENT_SPAN_ID = '1234567890123456'; test('continues the trace of injected meta tags instead of the server trace in a Pages Router page', async ({ page, }) => { + let serverSentryTrace: string | undefined; + // Stands in for a mobile SDK that injects the tags into the document of a WebView. await page.route('**/pages-router-ssr', async route => { const response = await route.fetch(); const html = await response.text(); + serverSentryTrace = html.match(/` + ``; @@ -39,20 +42,17 @@ test('continues the trace of injected meta tags instead of the server trace in a await route.fulfill({ response, body: html.replace('', `${metaTags}`) }); }); - const serverSpanPromise = waitForStreamedSpan('nextjs-16-standalone', span => { - return span.name === 'GET /pages-router-ssr' && getSpanOp(span) === HTTP_SERVER && span.is_segment; - }); - const pageloadSpanPromise = waitForStreamedSpan('nextjs-16-standalone', span => { return span.name === '/pages-router-ssr' && getSpanOp(span) === PAGELOAD && span.is_segment; }); await page.goto('/pages-router-ssr'); - const serverSpan = await serverSpanPromise; const pageloadSpan = await pageloadSpanPromise; - expect(serverSpan.trace_id).not.toBe(INJECTED_TRACE_ID); + // The document also carries the tags Next.js rendered for the request, which belong to the server trace. + expect(serverSentryTrace).toMatch(/^[0-9a-f]{32}-[0-9a-f]{16}/); + expect(serverSentryTrace).not.toContain(INJECTED_TRACE_ID); expect(pageloadSpan.trace_id).toBe(INJECTED_TRACE_ID); expect(pageloadSpan.parent_span_id).toBe(INJECTED_PARENT_SPAN_ID); }); From 59a675f051f07b01d2341dce451ff473431440a3 Mon Sep 17 00:00:00 2001 From: Charly Gomez Date: Thu, 26 Nov 2026 13:45:17 +0100 Subject: [PATCH 3/6] test(nextjs): Inject the trace meta tags with an init script in the E2E tests Chrome denies a document that Playwright fulfills the requests to the event proxy on localhost, so the pageload span never arrived. Co-Authored-By: Claude Fable 5.2 --- .../injected-trace-meta-tags.test.ts | 51 +++++++++++++------ .../tests/pages-router.test.ts | 51 +++++++++++++------ 2 files changed, 70 insertions(+), 32 deletions(-) diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts index 9b9c331ca692..f55b82c03ee8 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts @@ -18,19 +18,34 @@ test('Should continue the trace of injected meta tags instead of the server trac 'Next.js version does not support clientside instrumentation', ); - let serverSentryTrace: string | undefined; - - // Stands in for a mobile SDK that injects the tags into the document of a WebView. - await page.route('**/123/pages-router-client-trace-propagation', async route => { - const response = await route.fetch(); - const html = await response.text(); - serverSentryTrace = html.match(/` + - ``; - // After the tags Next.js renders for the request, so the order of the tags cannot decide the outcome. - await route.fulfill({ response, body: html.replace('', `${metaTags}`) }); - }); + // Stands in for a mobile SDK that injects the tags into the document of a WebView. They go after the tags Next.js + // renders for the request, so the order of the tags cannot decide the outcome. Rewriting the response instead is + // not an option: Chrome denies a document fulfilled by Playwright the requests to the event proxy on localhost. + await page.addInitScript( + ({ sentryTrace, baggage }) => { + const observer = new MutationObserver(() => { + const head = document.head; + if (!head?.querySelector('meta[name="sentry-trace"]') || !head.querySelector('meta[name="baggage"]')) { + return; + } + observer.disconnect(); + for (const [name, content] of [ + ['sentry-trace', sentryTrace], + ['baggage', baggage], + ] as const) { + const meta = document.createElement('meta'); + meta.name = name; + meta.content = content; + head.appendChild(meta); + } + }); + observer.observe(document, { childList: true, subtree: true }); + }, + { + sentryTrace: `${INJECTED_TRACE_ID}-${INJECTED_PARENT_SPAN_ID}-1`, + baggage: `sentry-trace_id=${INJECTED_TRACE_ID},sentry-sampled=true,sentry-sample_rate=1,sentry-environment=qa`, + }, + ); const pageloadSpanPromise = waitForStreamedSpan('nextjs-15', span => { return ( @@ -42,9 +57,13 @@ test('Should continue the trace of injected meta tags instead of the server trac const pageloadSpan = await pageloadSpanPromise; - // The document also carries the tags Next.js rendered for the request, which belong to the server trace. - expect(serverSentryTrace).toMatch(/^[0-9a-f]{32}-[0-9a-f]{16}/); - expect(serverSentryTrace).not.toContain(INJECTED_TRACE_ID); + const sentryTraceTags = await page + .locator('meta[name="sentry-trace"]') + .evaluateAll(tags => tags.map(tag => tag.getAttribute('content'))); + + expect(sentryTraceTags).toHaveLength(2); + expect(sentryTraceTags[0]).not.toContain(INJECTED_TRACE_ID); + expect(sentryTraceTags[1]).toContain(INJECTED_TRACE_ID); expect(pageloadSpan.trace_id).toBe(INJECTED_TRACE_ID); expect(pageloadSpan.parent_span_id).toBe(INJECTED_PARENT_SPAN_ID); }); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts index 5f69828bf88f..d92d7b2f4434 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts @@ -28,19 +28,34 @@ const INJECTED_PARENT_SPAN_ID = '1234567890123456'; test('continues the trace of injected meta tags instead of the server trace in a Pages Router page', async ({ page, }) => { - let serverSentryTrace: string | undefined; - - // Stands in for a mobile SDK that injects the tags into the document of a WebView. - await page.route('**/pages-router-ssr', async route => { - const response = await route.fetch(); - const html = await response.text(); - serverSentryTrace = html.match(/` + - ``; - // After the tags Next.js renders for the request, so the order of the tags cannot decide the outcome. - await route.fulfill({ response, body: html.replace('', `${metaTags}`) }); - }); + // Stands in for a mobile SDK that injects the tags into the document of a WebView. They go after the tags Next.js + // renders for the request, so the order of the tags cannot decide the outcome. Rewriting the response instead is + // not an option: Chrome denies a document fulfilled by Playwright the requests to the event proxy on localhost. + await page.addInitScript( + ({ sentryTrace, baggage }) => { + const observer = new MutationObserver(() => { + const head = document.head; + if (!head?.querySelector('meta[name="sentry-trace"]') || !head.querySelector('meta[name="baggage"]')) { + return; + } + observer.disconnect(); + for (const [name, content] of [ + ['sentry-trace', sentryTrace], + ['baggage', baggage], + ] as const) { + const meta = document.createElement('meta'); + meta.name = name; + meta.content = content; + head.appendChild(meta); + } + }); + observer.observe(document, { childList: true, subtree: true }); + }, + { + sentryTrace: `${INJECTED_TRACE_ID}-${INJECTED_PARENT_SPAN_ID}-1`, + baggage: `sentry-trace_id=${INJECTED_TRACE_ID},sentry-sampled=true,sentry-sample_rate=1,sentry-environment=qa`, + }, + ); const pageloadSpanPromise = waitForStreamedSpan('nextjs-16-standalone', span => { return span.name === '/pages-router-ssr' && getSpanOp(span) === PAGELOAD && span.is_segment; @@ -50,9 +65,13 @@ test('continues the trace of injected meta tags instead of the server trace in a const pageloadSpan = await pageloadSpanPromise; - // The document also carries the tags Next.js rendered for the request, which belong to the server trace. - expect(serverSentryTrace).toMatch(/^[0-9a-f]{32}-[0-9a-f]{16}/); - expect(serverSentryTrace).not.toContain(INJECTED_TRACE_ID); + const sentryTraceTags = await page + .locator('meta[name="sentry-trace"]') + .evaluateAll(tags => tags.map(tag => tag.getAttribute('content'))); + + expect(sentryTraceTags).toHaveLength(2); + expect(sentryTraceTags[0]).not.toContain(INJECTED_TRACE_ID); + expect(sentryTraceTags[1]).toContain(INJECTED_TRACE_ID); expect(pageloadSpan.trace_id).toBe(INJECTED_TRACE_ID); expect(pageloadSpan.parent_span_id).toBe(INJECTED_PARENT_SPAN_ID); }); From aa3348a35a2915402cf7cfe618649e329d767e7a Mon Sep 17 00:00:00 2001 From: Charly Gomez Date: Thu, 26 Nov 2026 15:04:46 +0100 Subject: [PATCH 4/6] test(nextjs): Log the trace carriers in the injected meta tag test (temporary) Co-Authored-By: Claude Fable 5.2 --- .../tests/pages-router/injected-trace-meta-tags.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts index f55b82c03ee8..357f0ada1986 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts @@ -53,7 +53,7 @@ test('Should continue the trace of injected meta tags instead of the server trac ); }); - await page.goto(`/123/pages-router-client-trace-propagation`); + const response = await page.goto(`/123/pages-router-client-trace-propagation`); const pageloadSpan = await pageloadSpanPromise; @@ -61,6 +61,12 @@ test('Should continue the trace of injected meta tags instead of the server trac .locator('meta[name="sentry-trace"]') .evaluateAll(tags => tags.map(tag => tag.getAttribute('content'))); + // TEMPORARY diagnostic for the Turbopack variant, to be removed. + console.log( + '[injected-trace-meta-tags]', + JSON.stringify({ serverTiming: response?.headers()['server-timing'], sentryTraceTags }), + ); + expect(sentryTraceTags).toHaveLength(2); expect(sentryTraceTags[0]).not.toContain(INJECTED_TRACE_ID); expect(sentryTraceTags[1]).toContain(INJECTED_TRACE_ID); From 9fb39e04ae1cc514aa749911c9e2e87d46d6765d Mon Sep 17 00:00:00 2001 From: Charly Gomez Date: Thu, 26 Nov 2026 15:09:12 +0100 Subject: [PATCH 5/6] test(nextjs): Log more of the pageload in the injected meta tag test (temporary) Co-Authored-By: Claude Fable 5.2 --- .../injected-trace-meta-tags.test.ts | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts index 357f0ada1986..d8a3f09edde6 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts @@ -62,9 +62,33 @@ test('Should continue the trace of injected meta tags instead of the server trac .evaluateAll(tags => tags.map(tag => tag.getAttribute('content'))); // TEMPORARY diagnostic for the Turbopack variant, to be removed. + const pageInfo = await page.evaluate(() => ({ + hasNextData: !!document.getElementById('__NEXT_DATA__'), + nextDataTrace: document.getElementById('__NEXT_DATA__')?.innerHTML.match(/_sentryTraceData":"([^"]+)"/)?.[1], + serverTiming: ( + performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined + )?.serverTiming?.map(entry => `${entry.name}=${entry.description.slice(0, 60)}`), + scripts: Array.from(document.scripts).map( + script => + `${script.async ? 'async ' : ''}${script.defer ? 'defer ' : ''}${script.src.split('/').pop() || script.id || 'inline'}`, + ), + headOrder: Array.from(document.head.children).map( + child => `${child.tagName}${child.getAttribute('name') ? `:${child.getAttribute('name')}` : ''}`, + ), + })); console.log( '[injected-trace-meta-tags]', - JSON.stringify({ serverTiming: response?.headers()['server-timing'], sentryTraceTags }), + JSON.stringify({ + serverTiming: response?.headers()['server-timing']?.slice(0, 80), + sentryTraceTags, + pageInfo, + pageloadSpan: { + trace_id: pageloadSpan.trace_id, + parent_span_id: pageloadSpan.parent_span_id, + links: pageloadSpan.links, + attributes: pageloadSpan.attributes, + }, + }), ); expect(sentryTraceTags).toHaveLength(2); From 3e59e9e65f73f16910313d8c8758d8f7b677ed73 Mon Sep 17 00:00:00 2001 From: Charly Gomez Date: Thu, 26 Nov 2026 15:15:46 +0100 Subject: [PATCH 6/6] test(nextjs): Give the injected meta tag test its own page URL Another test loads the same page in a parallel worker, and its pageload span matched this test's wait. Also removes the temporary logging. Co-Authored-By: Claude Fable 5.2 --- .../injected-trace-meta-tags.test.ts | 40 +++---------------- 1 file changed, 6 insertions(+), 34 deletions(-) diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts index d8a3f09edde6..4811d4854bef 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts @@ -1,4 +1,5 @@ import { expect, test } from '@playwright/test'; +import { URL_PATH } from '@sentry/conventions/attributes'; import { PAGELOAD } from '@sentry/conventions/op'; import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; import { parseSemver } from '@sentry/core'; @@ -7,6 +8,9 @@ const nextPackageJson = require('next/package.json'); const nextjsVersion = nextPackageJson.version; const { major, minor } = parseSemver(nextjsVersion); +// Another test loads this page in parallel, so the `[locale]` segment tells the pageload spans apart. +const PAGE_PATH = '/injected-meta-tags/pages-router-client-trace-propagation'; + const INJECTED_TRACE_ID = '12345678901234567890123456789012'; const INJECTED_PARENT_SPAN_ID = '1234567890123456'; @@ -48,12 +52,10 @@ test('Should continue the trace of injected meta tags instead of the server trac ); const pageloadSpanPromise = waitForStreamedSpan('nextjs-15', span => { - return ( - span.name === '/[locale]/pages-router-client-trace-propagation' && getSpanOp(span) === PAGELOAD && span.is_segment - ); + return getSpanOp(span) === PAGELOAD && span.is_segment && span.attributes?.[URL_PATH]?.value === PAGE_PATH; }); - const response = await page.goto(`/123/pages-router-client-trace-propagation`); + await page.goto(PAGE_PATH); const pageloadSpan = await pageloadSpanPromise; @@ -61,36 +63,6 @@ test('Should continue the trace of injected meta tags instead of the server trac .locator('meta[name="sentry-trace"]') .evaluateAll(tags => tags.map(tag => tag.getAttribute('content'))); - // TEMPORARY diagnostic for the Turbopack variant, to be removed. - const pageInfo = await page.evaluate(() => ({ - hasNextData: !!document.getElementById('__NEXT_DATA__'), - nextDataTrace: document.getElementById('__NEXT_DATA__')?.innerHTML.match(/_sentryTraceData":"([^"]+)"/)?.[1], - serverTiming: ( - performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined - )?.serverTiming?.map(entry => `${entry.name}=${entry.description.slice(0, 60)}`), - scripts: Array.from(document.scripts).map( - script => - `${script.async ? 'async ' : ''}${script.defer ? 'defer ' : ''}${script.src.split('/').pop() || script.id || 'inline'}`, - ), - headOrder: Array.from(document.head.children).map( - child => `${child.tagName}${child.getAttribute('name') ? `:${child.getAttribute('name')}` : ''}`, - ), - })); - console.log( - '[injected-trace-meta-tags]', - JSON.stringify({ - serverTiming: response?.headers()['server-timing']?.slice(0, 80), - sentryTraceTags, - pageInfo, - pageloadSpan: { - trace_id: pageloadSpan.trace_id, - parent_span_id: pageloadSpan.parent_span_id, - links: pageloadSpan.links, - attributes: pageloadSpan.attributes, - }, - }), - ); - expect(sentryTraceTags).toHaveLength(2); expect(sentryTraceTags[0]).not.toContain(INJECTED_TRACE_ID); expect(sentryTraceTags[1]).toContain(INJECTED_TRACE_ID);