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..4811d4854bef --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts @@ -0,0 +1,71 @@ +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'; + +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'; + +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. 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 getSpanOp(span) === PAGELOAD && span.is_segment && span.attributes?.[URL_PATH]?.value === PAGE_PATH; + }); + + await page.goto(PAGE_PATH); + + const pageloadSpan = await pageloadSpanPromise; + + 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 f9d268ada785..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 @@ -21,3 +21,57 @@ 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. 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; + }); + + await page.goto('/pages-router-ssr'); + + const pageloadSpan = await pageloadSpanPromise; + + 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/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 ?? ''}` : '