Skip to content

Commit 92c0117

Browse files
authored
feat(nextjs): Fork isolation scope for root spans on Next.js Node.js runtime (#13921)
We need to hoist the isolation scope forking logic out of the build-time instrumentation.
1 parent 496d98c commit 92c0117

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

packages/nextjs/src/server/index.ts

+21
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,28 @@ import {
33
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
44
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
55
applySdkMetadata,
6+
getCapturedScopesOnSpan,
67
getClient,
8+
getCurrentScope,
79
getGlobalScope,
10+
getIsolationScope,
811
getRootSpan,
12+
setCapturedScopesOnSpan,
913
spanToJSON,
1014
} from '@sentry/core';
1115
import { getDefaultIntegrations, httpIntegration, init as nodeInit } from '@sentry/node';
1216
import type { NodeClient, NodeOptions } from '@sentry/node';
1317
import { GLOBAL_OBJ, extractTraceparentData, logger, stripUrlQueryAndFragment } from '@sentry/utils';
1418

19+
import { context } from '@opentelemetry/api';
1520
import {
1621
ATTR_HTTP_REQUEST_METHOD,
1722
ATTR_HTTP_ROUTE,
1823
ATTR_URL_QUERY,
1924
SEMATTRS_HTTP_METHOD,
2025
SEMATTRS_HTTP_TARGET,
2126
} from '@opentelemetry/semantic-conventions';
27+
import { getScopesFromContext } from '@sentry/opentelemetry';
2228
import type { EventProcessor } from '@sentry/types';
2329
import { DEBUG_BUILD } from '../common/debug-build';
2430
import { devErrorSymbolicationEventProcessor } from '../common/devErrorSymbolicationEventProcessor';
@@ -221,6 +227,21 @@ export function init(options: NodeOptions): NodeClient | undefined {
221227
span.updateName('next server handler'); // This is all lowercase because the spans that Next.js emits by itself generally look like this.
222228
}
223229
}
230+
231+
// We want to fork the isolation scope for incoming requests
232+
if (spanAttributes?.['next.span_type'] === 'BaseServer.handleRequest' && span === getRootSpan(span)) {
233+
const scopes = getCapturedScopesOnSpan(span);
234+
235+
const isolationScope = (scopes.isolationScope || getIsolationScope()).clone();
236+
const scope = scopes.scope || getCurrentScope();
237+
238+
const currentScopesPointer = getScopesFromContext(context.active());
239+
if (currentScopesPointer) {
240+
currentScopesPointer.isolationScope = isolationScope;
241+
}
242+
243+
setCapturedScopesOnSpan(span, scope, isolationScope);
244+
}
224245
});
225246

226247
getGlobalScope().addEventProcessor(

0 commit comments

Comments
 (0)