Skip to content

Commit 18fef1c

Browse files
chargomeclaude
andcommitted
feat(nextjs): Never emit trace meta tags from a prerender
Under cacheComponents the SDK stopped enabling clientTraceMetadata, because a shell that Next.js prerenders inside one request is cached and served to later visitors, and a sentry-trace tag baked into it would replay that request's trace to all of them. ISR pages had the same problem, patched on the client by removing the tags on generateStaticParams routes. Next.js computes a document's trace tags inside the "prerender route (app)" span when it prerenders and outside of it when it renders for a request, including the resume of a shell. Register a SentryPropagator subclass that hands out no trace context while that span is active, so a prerendered shell never contains a trace and any tag that reaches the browser belongs to the current request. Only swap the propagator when the Node SDK registered its own, so a foreign OpenTelemetry setup stays untouched. Enable clientTraceMetadata again under cacheComponents and remove the client-side ISR heuristic together with the isrRoutes manifest field. The guard covers ISR shells as well, including revalidate routes without generateStaticParams. Refs #24944 Refs JS-3863 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 96b56c5 commit 18fef1c

41 files changed

Lines changed: 243 additions & 990 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44

55
- "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott
66

7+
- **feat(nextjs)**: Browser pageloads of apps with `cacheComponents` enabled now connect to the server request again. The SDK stopped emitting `sentry-trace` meta tags for these apps because a cached shell could replay the trace of the request that rendered it to every later visitor. The server SDK now refuses to hand out trace context while Next.js prerenders a document, so cached shells never carry a trace, and a tag that is in the document was always rendered for the current request. This also covers ISR pages, which no longer need the client-side meta tag removal based on `generateStaticParams`; the `isrRoutes` field of the injected route manifest is gone.
8+
9+
- **fix(cloudflare)**: Durable Object constructors now run in their own isolation scope. When work that the constructor starts, for example a `blockConcurrencyWhile` callback, calls a method of the instance, that call is no longer treated as an incoming RPC call, so an error the instance catches itself is no longer reported as unhandled. As a result, `Sentry.setTag()`, `setUser()` and `setContext()` in a constructor now apply only to that constructor work. They no longer reach later `fetch`, RPC or `alarm` invocations, because the scope they used to write to is shared by every Durable Object and handler in the isolate. Use `initialScope` for static data, and set per-instance data in each handler.
10+
711
## 11.5.0
812

913
### Important Changes

‎dev-packages/e2e-tests/test-applications/nextjs-15/tests/isr-routes.test.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,40 @@
11
import { expect, test } from '@playwright/test';
22
import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
33

4-
test('should remove sentry-trace and baggage meta tags on ISR dynamic route page load', async ({ page }) => {
4+
test('does not carry trace meta tags on an ISR dynamic route', async ({ page }) => {
5+
// The dev server renders ISR pages for every request, so there the trace tags are fresh and kept.
6+
test.skip(!!process.env.TEST_ENV?.includes('development'), 'ISR pages are only prerendered in production builds');
7+
58
// Navigate to ISR page
69
await page.goto('/isr-test/laptop');
710

811
// Wait for page to be fully loaded
912
await expect(page.locator('#isr-product-id')).toHaveText('laptop');
1013

11-
// Check that sentry-trace and baggage meta tags are removed for ISR pages
14+
// The shell was prerendered, and a prerender writes no trace tags
1215
await expect(page.locator('meta[name="sentry-trace"]')).toHaveCount(0);
1316
await expect(page.locator('meta[name="baggage"]')).toHaveCount(0);
1417
});
1518

16-
test('should remove sentry-trace and baggage meta tags on ISR static route', async ({ page }) => {
19+
test('does not carry trace meta tags on an ISR static route', async ({ page }) => {
20+
// The dev server renders ISR pages for every request, so there the trace tags are fresh and kept.
21+
test.skip(!!process.env.TEST_ENV?.includes('development'), 'ISR pages are only prerendered in production builds');
22+
1723
// Navigate to ISR static page
1824
await page.goto('/isr-test/static');
1925

2026
// Wait for page to be fully loaded
2127
await expect(page.locator('#isr-static-marker')).toHaveText('static-isr');
2228

23-
// Check that sentry-trace and baggage meta tags are removed for ISR pages
29+
// The shell was prerendered, and a prerender writes no trace tags
2430
await expect(page.locator('meta[name="sentry-trace"]')).toHaveCount(0);
2531
await expect(page.locator('meta[name="baggage"]')).toHaveCount(0);
2632
});
2733

28-
test('should remove meta tags for different ISR dynamic route values', async ({ page }) => {
34+
test('does not carry trace meta tags for different ISR dynamic route values', async ({ page }) => {
35+
// The dev server renders ISR pages for every request, so there the trace tags are fresh and kept.
36+
test.skip(!!process.env.TEST_ENV?.includes('development'), 'ISR pages are only prerendered in production builds');
37+
2938
// Test with 'phone' (one of the pre-generated static params)
3039
await page.goto('/isr-test/phone');
3140
await expect(page.locator('#isr-product-id')).toHaveText('phone');
@@ -44,7 +53,7 @@ test('should remove meta tags for different ISR dynamic route values', async ({
4453
test('should create unique traces for ISR pages on each visit', async ({ page }) => {
4554
const traceIds: string[] = [];
4655

47-
// Load the same ISR page 5 times to ensure cached HTML meta tags are consistently removed
56+
// Load the same ISR page 5 times: the cached HTML carries no trace tag, so every visit starts its own trace
4857
for (let i = 0; i < 5; i++) {
4958
const spanPromise = waitForStreamedSpan('nextjs-15', span => {
5059
return span.name === '/isr-test/:product' && getSpanOp(span) === 'pageload' && span.is_segment;
@@ -64,7 +73,7 @@ test('should create unique traces for ISR pages on each visit', async ({ page })
6473
traceIds.push(traceId!);
6574
}
6675

67-
// Verify all 5 page loads have unique trace IDs (no reuse of cached/stale meta tags)
76+
// Verify all 5 page loads have unique trace IDs (no trace replayed from the cached HTML)
6877
const uniqueTraceIds = new Set(traceIds);
6978
expect(uniqueTraceIds.size).toBe(5);
7079
});

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

Lines changed: 0 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -81,38 +81,6 @@ test('Should generate metadata async', async ({ page }) => {
8181
await expect(page).toHaveTitle('Product: 1');
8282
});
8383

84-
test('Prerendered shell does not stitch the pageload onto a stale trace', async ({ page }) => {
85-
const serverTxPromise = waitForTransaction('nextjs-16-cacheComponents', async transactionEvent => {
86-
return (
87-
transactionEvent.contexts?.trace?.op === 'http.server' && transactionEvent.transaction === 'GET /pageload-tracing'
88-
);
89-
});
90-
91-
const pageloadTxPromise = waitForTransaction('nextjs-16-cacheComponents', async transactionEvent => {
92-
return transactionEvent.contexts?.trace?.op === 'pageload' && transactionEvent.transaction === '/pageload-tracing';
93-
});
94-
95-
await page.goto('/pageload-tracing');
96-
97-
await expect(page.locator('#todos-fetched')).toHaveText('Todos fetched: 5');
98-
99-
const [serverTx, pageloadTx] = await Promise.all([serverTxPromise, pageloadTxPromise]);
100-
101-
const serverTraceId = serverTx.contexts?.trace?.trace_id;
102-
const pageloadTraceId = pageloadTx.contexts?.trace?.trace_id;
103-
104-
// Under Cache Components the shell is prerendered and rendered in a context detached from the
105-
// runtime server request, so a `sentry-trace` meta tag would carry a stale/unrelated trace. The
106-
// SDK therefore does not enable the trace meta tags, and the browser pageload starts a fresh trace
107-
// instead of stitching onto a trace that doesn't match the server request.
108-
expect(pageloadTraceId).toBeTruthy();
109-
expect(serverTraceId).not.toBe(pageloadTraceId);
110-
111-
// No trace meta tags should be injected when Cache Components is enabled.
112-
expect(await page.locator('meta[name="sentry-trace"]').count()).toBe(0);
113-
expect(await page.locator('meta[name="baggage"]').count()).toBe(0);
114-
});
115-
11684
test('Should prerender a page that captures an exception in generateMetadata', async ({ page }) => {
11785
await page.goto('/capture-metadata');
11886

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { expect, test } from '@playwright/test';
22
import { waitForTransaction } from '@sentry-internal/test-utils';
33

4-
// TODO: Remove the inverse assertion in cacheComponents.spec.ts ("Prerendered shell does not stitch the pageload onto a stale trace") when this test passes.
54
test('connects the pageload trace to the runtime server request', async ({ page }) => {
6-
test.fail();
5+
// The resumed part of the document, which carries the tag, arrives after the SDK started. Enabled
6+
// once the pageload instrumentation waits for it.
7+
test.skip(true, 'Needs the deferred pageload start');
78

89
// The shell is prerendered, but the page's dynamic part (`DynamicContent` awaits `headers()`)
910
// runs on the server on every request and produces the `GET /pageload-tracing` transaction.

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

Lines changed: 1 addition & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { expect, test } from '@playwright/test';
2-
import { getSpanOp, waitForError, waitForStreamedSpan, waitForStreamedSpans } from '@sentry-internal/test-utils';
2+
import { getSpanOp, waitForError, waitForStreamedSpans } from '@sentry-internal/test-utils';
33

44
test('Should render cached component', async ({ page }) => {
55
const spansPromise = waitForStreamedSpans('nextjs-16-streaming-cacheComponents', spans => {
@@ -93,38 +93,6 @@ test('Should generate metadata async', async ({ page }) => {
9393
await expect(page).toHaveTitle('Product: 1');
9494
});
9595

96-
test('Prerendered shell does not stitch the pageload onto a stale trace', async ({ page }) => {
97-
const serverSpanPromise = waitForStreamedSpan('nextjs-16-streaming-cacheComponents', span => {
98-
return span.name === 'GET /pageload-tracing' && getSpanOp(span) === 'http.server' && span.is_segment;
99-
});
100-
101-
const pageloadSpanPromise = waitForStreamedSpan('nextjs-16-streaming-cacheComponents', span => {
102-
return span.name === '/pageload-tracing' && getSpanOp(span) === 'pageload' && span.is_segment;
103-
});
104-
105-
await page.goto('/pageload-tracing');
106-
107-
await expect(page.locator('#todos-fetched')).toHaveText('Todos fetched: 5');
108-
109-
const [serverSpan, pageloadSpan] = await Promise.all([serverSpanPromise, pageloadSpanPromise]);
110-
111-
expect(pageloadSpan.attributes).toMatchObject({
112-
['sentry.segment.name.source']: { value: 'route', type: 'string' },
113-
['url.path']: { value: '/pageload-tracing', type: 'string' },
114-
['url.template']: { value: '/pageload-tracing', type: 'string' },
115-
});
116-
// Under Cache Components the can be prerendered and rendered in a context detached from the
117-
// runtime server request, so a `sentry-trace` meta tag would carry a stale/unrelated trace. The
118-
// SDK therefore does not enable the trace meta tags, and the browser pageload starts a fresh trace
119-
// instead of stitching onto a trace that doesn't match the server request.
120-
expect(pageloadSpan.trace_id).toBeTruthy();
121-
expect(serverSpan.trace_id).not.toBe(pageloadSpan.trace_id);
122-
123-
// No trace meta tags should be injected when Cache Components is enabled.
124-
expect(await page.locator('meta[name="sentry-trace"]').count()).toBe(0);
125-
expect(await page.locator('meta[name="baggage"]').count()).toBe(0);
126-
});
127-
12896
test('Should prerender a page that captures an exception in generateMetadata', async ({ page }) => {
12997
await page.goto('/capture-metadata');
13098

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { expect, test } from '@playwright/test';
22
import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
33

4-
// TODO: Remove the inverse assertion in cacheComponents.spec.ts ("Prerendered shell does not stitch the pageload onto a stale trace") when this test passes.
54
test('connects the pageload trace to the runtime server request', async ({ page }) => {
6-
test.fail();
5+
// The resumed part of the document, which carries the tag, arrives after the SDK started. Enabled
6+
// once the pageload instrumentation waits for it.
7+
test.skip(true, 'Needs the deferred pageload start');
78

89
// The shell is prerendered, but the page's dynamic part (`DynamicContent` awaits `headers()`)
910
// runs on the server on every request and produces the `GET /pageload-tracing` root span.

‎dev-packages/e2e-tests/test-applications/nextjs-16/tests/isr-routes.test.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,40 @@
11
import { expect, test } from '@playwright/test';
22
import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
33

4-
test('should remove sentry-trace and baggage meta tags on ISR dynamic route page load', async ({ page }) => {
4+
test('does not carry trace meta tags on an ISR dynamic route', async ({ page }) => {
5+
// The dev server renders ISR pages for every request, so there the trace tags are fresh and kept.
6+
test.skip(!!process.env.TEST_ENV?.includes('development'), 'ISR pages are only prerendered in production builds');
7+
58
// Navigate to ISR page
69
await page.goto('/isr-test/laptop');
710

811
// Wait for page to be fully loaded
912
await expect(page.locator('#isr-product-id')).toHaveText('laptop');
1013

11-
// Check that sentry-trace and baggage meta tags are removed for ISR pages
14+
// The shell was prerendered, and a prerender writes no trace tags
1215
await expect(page.locator('meta[name="sentry-trace"]')).toHaveCount(0);
1316
await expect(page.locator('meta[name="baggage"]')).toHaveCount(0);
1417
});
1518

16-
test('should remove sentry-trace and baggage meta tags on ISR static route', async ({ page }) => {
19+
test('does not carry trace meta tags on an ISR static route', async ({ page }) => {
20+
// The dev server renders ISR pages for every request, so there the trace tags are fresh and kept.
21+
test.skip(!!process.env.TEST_ENV?.includes('development'), 'ISR pages are only prerendered in production builds');
22+
1723
// Navigate to ISR static page
1824
await page.goto('/isr-test/static');
1925

2026
// Wait for page to be fully loaded
2127
await expect(page.locator('#isr-static-marker')).toHaveText('static-isr');
2228

23-
// Check that sentry-trace and baggage meta tags are removed for ISR pages
29+
// The shell was prerendered, and a prerender writes no trace tags
2430
await expect(page.locator('meta[name="sentry-trace"]')).toHaveCount(0);
2531
await expect(page.locator('meta[name="baggage"]')).toHaveCount(0);
2632
});
2733

28-
test('should remove meta tags for different ISR dynamic route values', async ({ page }) => {
34+
test('does not carry trace meta tags for different ISR dynamic route values', async ({ page }) => {
35+
// The dev server renders ISR pages for every request, so there the trace tags are fresh and kept.
36+
test.skip(!!process.env.TEST_ENV?.includes('development'), 'ISR pages are only prerendered in production builds');
37+
2938
// Test with 'phone' (one of the pre-generated static params)
3039
await page.goto('/isr-test/phone');
3140
await expect(page.locator('#isr-product-id')).toHaveText('phone');
@@ -44,7 +53,7 @@ test('should remove meta tags for different ISR dynamic route values', async ({
4453
test('should create unique traces for ISR pages on each visit', async ({ page }) => {
4554
const traceIds: string[] = [];
4655

47-
// Load the same ISR page 5 times to ensure cached HTML meta tags are consistently removed
56+
// Load the same ISR page 5 times: the cached HTML carries no trace tag, so every visit starts its own trace
4857
for (let i = 0; i < 5; i++) {
4958
const spanPromise = waitForStreamedSpan('nextjs-16', span => {
5059
return span.name === '/isr-test/:product' && getSpanOp(span) === 'pageload' && span.is_segment;
@@ -64,7 +73,7 @@ test('should create unique traces for ISR pages on each visit', async ({ page })
6473
traceIds.push(traceId!);
6574
}
6675

67-
// Verify all 5 page loads have unique trace IDs (no reuse of cached/stale meta tags)
76+
// Verify all 5 page loads have unique trace IDs (no trace replayed from the cached HTML)
6877
const uniqueTraceIds = new Set(traceIds);
6978
expect(uniqueTraceIds.size).toBe(5);
7079
});

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

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import { getClientVercelEnv } from '../common/getVercelEnv';
1111
import { isRedirectNavigationError } from '../common/nextNavigationErrorUtils';
1212
import { browserTracingIntegration } from './browserTracingIntegration';
1313
import { nextjsClientStackFrameNormalizationIntegration } from './clientNormalizationIntegration';
14-
import { removeIsrSsgTraceMetaTags } from './routing/isrRoutingTracing';
1514
import { createNextRouteProvider } from './routing/routeProvider';
1615
import { applyTunnelRouteOption } from './tunnelRoute';
1716

@@ -44,12 +43,6 @@ export function init(options: BrowserOptions): Client | undefined {
4443
});
4544
}
4645

47-
// Remove cached trace meta tags for ISR/SSG pages before initializing
48-
// This prevents the browser tracing integration from using stale trace IDs
49-
if (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) {
50-
removeIsrSsgTraceMetaTags();
51-
}
52-
5346
const opts = {
5447
environment: options.environment || process.env.SENTRY_ENVIRONMENT || getClientVercelEnv() || process.env.NODE_ENV,
5548
defaultIntegrations: getDefaultIntegrations(options),

‎packages/nextjs/src/client/routing/isrRoutingTracing.ts‎

Lines changed: 0 additions & 63 deletions
This file was deleted.

‎packages/nextjs/src/client/routing/parameterization.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,6 @@ export function getManifest(): RouteManifest | null {
147147
let manifest: RouteManifest = {
148148
staticRoutes: [],
149149
dynamicRoutes: [],
150-
isrRoutes: [],
151150
};
152151

153152
// Shallow check if the manifest is actually what we expect it to be

0 commit comments

Comments
 (0)