Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
@@ -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);
});
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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]`.
*
Expand Down
17 changes: 13 additions & 4 deletions packages/nextjs/src/client/routing/traceMetaTags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
115 changes: 114 additions & 1 deletion packages/nextjs/test/performance/pagesRouterInstrumentation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ describe('pagesRouterInstrumentPageLoad', () => {
props?: any;
navigatableRoutes?: string[];
hasNextData: boolean;
head?: string;
}) {
const nextDataContent: NEXT_DATA = {
props: pageProperties.props,
Expand All @@ -73,7 +74,7 @@ describe('pagesRouterInstrumentPageLoad', () => {
const dom = new JSDOM(
// Just an example of what a __NEXT_DATA__ tag might look like
pageProperties.hasNextData
? `<body><script id="__NEXT_DATA__" type="application/json">${JSON.stringify(nextDataContent)}</script></body>`
? `<head>${pageProperties.head ?? ''}</head><body><script id="__NEXT_DATA__" type="application/json">${JSON.stringify(nextDataContent)}</script></body>`
: '<body><h1>No next data :(</h1></body>',
{ url: pageProperties.url },
);
Expand Down Expand Up @@ -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 = `<meta name="sentry-trace" content="${SERVER_TRACE_ID}-b855953cd3394d5f-1"><meta name="baggage" content="sentry-trace_id=${SERVER_TRACE_ID},sentry-release=2.1.0">`;
const foreignTrace = {
sentryTrace: `${FOREIGN_TRACE_ID}-1234567890123456-1`,
baggage: `sentry-trace_id=${FOREIGN_TRACE_ID},sentry-release=mobile`,
};
const foreignMetaTags = `<meta name="sentry-trace" content="${foreignTrace.sentryTrace}"><meta name="baggage" content="${foreignTrace.baggage}">`;

function instrumentPageLoad(
head: string,
pageProps: Record<string, unknown> = {
_sentryTraceData: nextDataTrace.sentryTrace,
_sentryBaggage: nextDataTrace.baggage,
},
route = '/some-page',
): ReturnType<typeof vi.fn> {
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', '<meta name="sentry-trace" content="">'],
['a `sentry-trace` meta tag without content', '<meta name="sentry-trace">'],
['an invalid `sentry-trace` meta tag', '<meta name="sentry-trace" content="not-a-trace">'],
[
'a `sentry-trace` meta tag of another trace without its baggage',
`${serverMetaTags}<meta name="sentry-trace" content="${foreignTrace.sentryTrace}">`,
],
['only a `baggage` meta tag of another trace', `<meta name="baggage" content="${foreignTrace.baggage}">`],
['unrelated meta tags', '<meta name="viewport" content="width=device-width">'],
])('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', () => {
Expand Down
Loading