-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(nextjs): Add URL to tags of server components and generation functions issues #16500
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
Changes from all commits
27392bb
4931899
9ca3dc1
0bdc3b5
c36a202
67462de
9692302
e47877c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
import { getSanitizedUrlStringFromUrlObject, parseStringToURLObject } from '@sentry/core'; | ||
|
||
type ComponentRouteParams = Record<string, string> | undefined; | ||
type HeadersDict = Record<string, string> | undefined; | ||
|
||
const HeaderKeys = { | ||
FORWARDED_PROTO: 'x-forwarded-proto', | ||
FORWARDED_HOST: 'x-forwarded-host', | ||
HOST: 'host', | ||
REFERER: 'referer', | ||
} as const; | ||
|
||
/** | ||
* Replaces route parameters in a path template with their values | ||
* @param path - The path template containing parameters in [paramName] format | ||
* @param params - Optional route parameters to replace in the template | ||
* @returns The path with parameters replaced | ||
*/ | ||
export function substituteRouteParams(path: string, params?: ComponentRouteParams): string { | ||
if (!params || typeof params !== 'object') return path; | ||
|
||
let resultPath = path; | ||
for (const [key, value] of Object.entries(params)) { | ||
resultPath = resultPath.split(`[${key}]`).join(encodeURIComponent(value)); | ||
} | ||
return resultPath; | ||
} | ||
|
||
/** | ||
* Normalizes a path by removing route groups | ||
* @param path - The path to normalize | ||
* @returns The normalized path | ||
*/ | ||
export function sanitizeRoutePath(path: string): string { | ||
const cleanedSegments = path | ||
.split('/') | ||
.filter(segment => segment && !(segment.startsWith('(') && segment.endsWith(')'))); | ||
|
||
return cleanedSegments.length > 0 ? `/${cleanedSegments.join('/')}` : '/'; | ||
} | ||
|
||
/** | ||
* Constructs a full URL from the component route, parameters, and headers. | ||
* | ||
* @param componentRoute - The route template to construct the URL from | ||
* @param params - Optional route parameters to replace in the template | ||
* @param headersDict - Optional headers containing protocol and host information | ||
* @param pathname - Optional pathname coming from parent span "http.target" | ||
* @returns A sanitized URL string | ||
*/ | ||
export function buildUrlFromComponentRoute( | ||
componentRoute: string, | ||
params?: ComponentRouteParams, | ||
headersDict?: HeadersDict, | ||
pathname?: string, | ||
): string { | ||
const parameterizedPath = substituteRouteParams(componentRoute, params); | ||
// If available, the pathname from the http.target of the HTTP request server span takes precedence over the parameterized path. | ||
// Spans such as generateMetadata and Server Component rendering are typically direct children of that span. | ||
const path = pathname ?? sanitizeRoutePath(parameterizedPath); | ||
|
||
const protocol = headersDict?.[HeaderKeys.FORWARDED_PROTO]; | ||
const host = headersDict?.[HeaderKeys.FORWARDED_HOST] || headersDict?.[HeaderKeys.HOST]; | ||
|
||
if (!protocol || !host) { | ||
return path; | ||
} | ||
|
||
const fullUrl = `${protocol}://${host}${path}`; | ||
|
||
const urlObject = parseStringToURLObject(fullUrl); | ||
if (!urlObject) { | ||
return path; | ||
} | ||
|
||
return getSanitizedUrlStringFromUrlObject(urlObject); | ||
} | ||
|
||
/** | ||
* Returns a sanitized URL string from the referer header if it exists and is valid. | ||
* | ||
* @param headersDict - Optional headers containing the referer | ||
* @returns A sanitized URL string or undefined if referer is missing/invalid | ||
*/ | ||
export function extractSanitizedUrlFromRefererHeader(headersDict?: HeadersDict): string | undefined { | ||
const referer = headersDict?.[HeaderKeys.REFERER]; | ||
if (!referer) { | ||
return undefined; | ||
} | ||
|
||
try { | ||
const refererUrl = new URL(referer); | ||
return getSanitizedUrlStringFromUrlObject(refererUrl); | ||
} catch (error) { | ||
return undefined; | ||
} | ||
} | ||
|
||
/** | ||
* Returns a sanitized URL string using the referer header if available, | ||
* otherwise constructs the URL from the component route, params, and headers. | ||
* | ||
* @param componentRoute - The route template to construct the URL from | ||
* @param params - Optional route parameters to replace in the template | ||
* @param headersDict - Optional headers containing protocol, host, and referer | ||
* @param pathname - Optional pathname coming from root span "http.target" | ||
* @returns A sanitized URL string | ||
*/ | ||
export function getSanitizedRequestUrl( | ||
componentRoute: string, | ||
params?: ComponentRouteParams, | ||
headersDict?: HeadersDict, | ||
pathname?: string, | ||
): string { | ||
const refererUrl = extractSanitizedUrlFromRefererHeader(headersDict); | ||
if (refererUrl) { | ||
return refererUrl; | ||
} | ||
|
||
return buildUrlFromComponentRoute(componentRoute, params, headersDict, pathname); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,6 +13,7 @@ import { | |
setCapturedScopesOnSpan, | ||
SPAN_STATUS_ERROR, | ||
SPAN_STATUS_OK, | ||
spanToJSON, | ||
startSpanManual, | ||
winterCGHeadersToDict, | ||
withIsolationScope, | ||
|
@@ -22,7 +23,7 @@ import type { GenerationFunctionContext } from '../common/types'; | |
import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavigationErrorUtils'; | ||
import { TRANSACTION_ATTR_SENTRY_TRACE_BACKFILL } from './span-attributes-with-logic-attached'; | ||
import { commonObjectToIsolationScope, commonObjectToPropagationContext } from './utils/tracingUtils'; | ||
|
||
import { getSanitizedRequestUrl } from './utils/urls'; | ||
/** | ||
* Wraps a generation function (e.g. generateMetadata) with Sentry error and performance instrumentation. | ||
*/ | ||
|
@@ -44,14 +45,23 @@ export function wrapGenerationFunctionWithSentry<F extends (...args: any[]) => a | |
} | ||
|
||
const isolationScope = commonObjectToIsolationScope(headers); | ||
let pathname = undefined as string | undefined; | ||
|
||
const activeSpan = getActiveSpan(); | ||
if (activeSpan) { | ||
const rootSpan = getRootSpan(activeSpan); | ||
const { scope } = getCapturedScopesOnSpan(rootSpan); | ||
setCapturedScopesOnSpan(rootSpan, scope ?? new Scope(), isolationScope); | ||
|
||
const spanData = spanToJSON(rootSpan); | ||
|
||
if (spanData.data && 'http.target' in spanData.data) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. l: this can be simplified to: if (typeof spanData.data['http.target'] === 'string') {
pathname = spanData.data['http.target'];
}
|
||
pathname = spanData.data['http.target'] as string; | ||
} | ||
} | ||
|
||
const headersDict = headers ? winterCGHeadersToDict(headers) : undefined; | ||
|
||
let data: Record<string, unknown> | undefined = undefined; | ||
if (getClient()?.getOptions().sendDefaultPii) { | ||
const props: unknown = args[0]; | ||
|
@@ -61,15 +71,19 @@ export function wrapGenerationFunctionWithSentry<F extends (...args: any[]) => a | |
data = { params, searchParams }; | ||
} | ||
|
||
const headersDict = headers ? winterCGHeadersToDict(headers) : undefined; | ||
|
||
return withIsolationScope(isolationScope, () => { | ||
return withScope(scope => { | ||
scope.setTransactionName(`${componentType}.${generationFunctionIdentifier} (${componentRoute})`); | ||
|
||
isolationScope.setSDKProcessingMetadata({ | ||
normalizedRequest: { | ||
headers: headersDict, | ||
url: getSanitizedRequestUrl( | ||
componentRoute, | ||
data?.params as Record<string, string> | undefined, | ||
headersDict, | ||
pathname, | ||
), | ||
} satisfies RequestEventData, | ||
}); | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,7 @@ import { | |
captureException, | ||
getActiveSpan, | ||
getCapturedScopesOnSpan, | ||
getClient, | ||
getRootSpan, | ||
handleCallbackErrors, | ||
propagationContextFromHeaders, | ||
|
@@ -12,6 +13,7 @@ import { | |
setCapturedScopesOnSpan, | ||
SPAN_STATUS_ERROR, | ||
SPAN_STATUS_OK, | ||
spanToJSON, | ||
startSpanManual, | ||
vercelWaitUntil, | ||
winterCGHeadersToDict, | ||
|
@@ -23,6 +25,7 @@ import type { ServerComponentContext } from '../common/types'; | |
import { TRANSACTION_ATTR_SENTRY_TRACE_BACKFILL } from './span-attributes-with-logic-attached'; | ||
import { flushSafelyWithTimeout } from './utils/responseEnd'; | ||
import { commonObjectToIsolationScope, commonObjectToPropagationContext } from './utils/tracingUtils'; | ||
import { getSanitizedRequestUrl } from './utils/urls'; | ||
|
||
/** | ||
* Wraps an `app` directory server component with Sentry error instrumentation. | ||
|
@@ -41,18 +44,36 @@ export function wrapServerComponentWithSentry<F extends (...args: any[]) => any> | |
const requestTraceId = getActiveSpan()?.spanContext().traceId; | ||
const isolationScope = commonObjectToIsolationScope(context.headers); | ||
|
||
let pathname = undefined as string | undefined; | ||
const activeSpan = getActiveSpan(); | ||
if (activeSpan) { | ||
const rootSpan = getRootSpan(activeSpan); | ||
const { scope } = getCapturedScopesOnSpan(rootSpan); | ||
setCapturedScopesOnSpan(rootSpan, scope ?? new Scope(), isolationScope); | ||
|
||
const spanData = spanToJSON(rootSpan); | ||
|
||
if (spanData.data && 'http.target' in spanData.data) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same here as above :) |
||
pathname = spanData.data['http.target']?.toString(); | ||
} | ||
} | ||
|
||
const headersDict = context.headers ? winterCGHeadersToDict(context.headers) : undefined; | ||
|
||
let params: Record<string, string> | undefined = undefined; | ||
|
||
if (getClient()?.getOptions().sendDefaultPii) { | ||
const props: unknown = args[0]; | ||
params = | ||
props && typeof props === 'object' && 'params' in props | ||
? (props.params as Record<string, string>) | ||
: undefined; | ||
} | ||
|
||
isolationScope.setSDKProcessingMetadata({ | ||
normalizedRequest: { | ||
headers: headersDict, | ||
url: getSanitizedRequestUrl(componentRoute, params, headersDict, pathname), | ||
} satisfies RequestEventData, | ||
}); | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
l: I would always mention here if things are only exported for tests, for clarity. In this file, I believe only
getSanitizedRequestUrl
is actually used, all the other exports are for tests only right? By mentioning this with each export is is easier to follow why things are exported (vs. "hey can I un-export this because it is not actually used anyhwere?")