Skip to content

feat(nextjs): Fork isolation scope for root spans on Next.js edge runtime #13919

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 10, 2024
Merged
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
1 change: 1 addition & 0 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"access": "public"
},
"dependencies": {
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/instrumentation-http": "0.53.0",
"@opentelemetry/semantic-conventions": "^1.27.0",
"@rollup/plugin-commonjs": "26.0.1",
Expand Down
32 changes: 30 additions & 2 deletions packages/nextjs/src/edge/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import { applySdkMetadata, registerSpanErrorInstrumentation } from '@sentry/core';
import { context } from '@opentelemetry/api';
import {
applySdkMetadata,
getCapturedScopesOnSpan,
getCurrentScope,
getIsolationScope,
getRootSpan,
registerSpanErrorInstrumentation,
setCapturedScopesOnSpan,
} from '@sentry/core';

import { GLOBAL_OBJ } from '@sentry/utils';
import type { VercelEdgeOptions } from '@sentry/vercel-edge';
import { getDefaultIntegrations, init as vercelEdgeInit } from '@sentry/vercel-edge';

import { getScopesFromContext } from '@sentry/opentelemetry';
import { isBuild } from '../common/utils/isBuild';
import { distDirRewriteFramesIntegration } from './distDirRewriteFramesIntegration';

Expand Down Expand Up @@ -39,7 +50,24 @@ export function init(options: VercelEdgeOptions = {}): void {

applySdkMetadata(opts, 'nextjs');

vercelEdgeInit(opts);
const client = vercelEdgeInit(opts);

// Create/fork an isolation whenever we create root spans. This is ok because in Next.js we only create root spans on the edge for incoming requests.
client?.on('spanStart', span => {
if (span === getRootSpan(span)) {
const scopes = getCapturedScopesOnSpan(span);

const isolationScope = (scopes.isolationScope || getIsolationScope()).clone();
const scope = scopes.scope || getCurrentScope();

const currentScopesPointer = getScopesFromContext(context.active());
if (currentScopesPointer) {
currentScopesPointer.isolationScope = isolationScope;
}

setCapturedScopesOnSpan(span, scope, isolationScope);
}
});
}

/**
Expand Down
Loading