Skip to content

fix(nextjs): Fix conditional root span handling for route handlers #11608

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 1 commit into from
Apr 15, 2024
Merged
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
46 changes: 28 additions & 18 deletions packages/nextjs/src/common/wrapRouteHandlerWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
getRootSpan,
handleCallbackErrors,
setHttpStatus,
spanToJSON,
startSpan,
} from '@sentry/core';
import type { Span } from '@sentry/types';
Expand All @@ -24,32 +25,41 @@ function startOrUpdateSpan(spanName: string, cb: (rootSpan: Span) => Promise<Res
const activeSpan = getActiveSpan();
const rootSpan = activeSpan && getRootSpan(activeSpan);

if (rootSpan) {
rootSpan.updateName(spanName);
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs',
});
// We have different possible scenarios here:
// 1. If we have no root span, we just create a new span
// 2. We have a root span that that we want to update here
// 3. We have a root span that was already updated (e.g. if this is a nested call)

return cb(rootSpan);
} else {
const attributes = {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs',
} as const;

if (!rootSpan) {
return startSpan(
{
op: 'http.server',
name: spanName,
forceTransaction: true,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs',
},
},
(span: Span) => {
return cb(span);
attributes,
},
cb,
);
}

// If `op` is set, we assume this was already processed before
// Probably this is a nested call, no need to update anything anymore
// OR, if we don't have next.span_type, we don't know where this comes from and don't want to mess with it
const existingAttributes = spanToJSON(rootSpan).data || {};
if (existingAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !existingAttributes['next.span_type']) {
return cb(rootSpan);
}

// Finally, we want to update the root span, as the ones generated by next are often not good enough for us
rootSpan.updateName(spanName);
rootSpan.setAttributes(attributes);

return cb(rootSpan);
}

/**
Expand Down