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
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ test('Sends parameterized transaction name to Sentry', async ({ page }) => {

expect(transaction).toBeDefined();
expect(transaction.transaction).toBe('GET user/:id');
expect(transaction.contexts?.trace?.data?.['http.route']).toBe('user/:id');
});

test('Sends form data with action span', async ({ page }) => {
Expand DownExpand Up@@ -271,6 +272,7 @@ test('Sends two linked transactions (server & client) to Sentry', async ({ page
const pageLoadParentSpanId = pageloadTransaction.contexts?.trace?.parent_span_id;

expect(httpServerTransaction.transaction).toBe('GET http://localhost:3030/');
expect(httpServerTransaction.contexts?.trace?.data?.['http.route']).toBeUndefined();
expect(pageloadTransaction.transaction).toBe('/');

expect(httpServerTraceId).toBeDefined();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,7 +42,7 @@ test('should trace orpc server component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/list',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand DownExpand Up@@ -99,7 +99,7 @@ test('should trace orpc client component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/find',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand Down
16 changes: 11 additions & 5 deletions packages/elysia/src/withElysia.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import {
captureException,
Expand DownExpand Up@@ -60,18 +60,24 @@ const instrumentedApps = new WeakSet<Elysia>();
function updateRouteTransactionName(request: Request, method: string, route: string): void {
const transactionName = `${method} ${route}`;

function applyRouteToSpan(span: Span): void {
updateSpanName(span, transactionName);
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

// Try the stored root span first (reliable across async contexts),
// then fall back to getActiveSpan() for cases where async context is preserved.
const rootSpan = rootSpanForRequest.get(request);
if (rootSpan) {
updateSpanName(rootSpan, transactionName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(rootSpan);
} else {
const activeSpan = getActiveSpan();
if (activeSpan) {
const root = getRootSpan(activeSpan);
updateSpanName(root, transactionName);
root.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(root);
}
}

Expand Down
26 changes: 26 additions & 0 deletions packages/elysia/test/withElysia.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import type { ErrorContext } from 'elysia';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

Expand DownExpand Up@@ -32,6 +33,12 @@ const mockGetIsolationScope = vi.fn(() => ({
const mockGetClient = vi.fn(() => ({
on: vi.fn(),
}));
const mockRootSpan = {
setAttributes: vi.fn(),
updateName: vi.fn(),
};
const mockGetActiveSpan = vi.fn();
const mockGetRootSpan = vi.fn(() => mockRootSpan);
const mockGetTraceData = vi.fn(() => ({
'sentry-trace': 'abc123-def456-1',
baggage: 'sentry-environment=test,sentry-trace_id=abc123',
Expand All@@ -43,8 +50,10 @@ vi.mock('@sentry/core', async importActual => {
return {
...actual,
captureException: (...args: unknown[]) => mockCaptureException(...args),
getActiveSpan: () => mockGetActiveSpan(),
getIsolationScope: () => mockGetIsolationScope(),
getClient: () => mockGetClient(),
getRootSpan: () => mockGetRootSpan(),
getTraceData: () => mockGetTraceData(),
};
});
Expand DownExpand Up@@ -88,6 +97,23 @@ describe('withElysia', () => {
expect(headers['baggage']).toBe('sentry-environment=test,sentry-trace_id=abc123');
});

it('sets the matched route on the root span', () => {
mockGetActiveSpan.mockReturnValueOnce(mockRootSpan);
// @ts-expect-error - mock app
withElysia(mockApp);

onAfterHandleHandler({
route: '/users/:id',
request: new Request('https://example.com/users/42', { method: 'GET' }),
set: { headers: {} },
});

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/users/:id',
});
});

it('does not set headers when trace data is empty', () => {
mockGetTraceData.mockReturnValueOnce({});
// @ts-expect-error - mock app
Expand Down
3 changes: 2 additions & 1 deletion packages/hono/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -92,7 +92,8 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"@sentry/conventions": "^0.16.0"
},
"peerDependencies": {
"@cloudflare/workers-types": "^4.x",
Expand Down
9 changes: 7 additions & 2 deletions packages/hono/src/shared/middlewareHandlers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import { defaultShouldHandleError } from './defaultShouldHandleError';
import { resolveRouteName } from './resolveRouteName';
import { type SentryHonoMiddlewareOptions } from '../shared/types';
import { type GetConnInfo } from 'hono/conninfo';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Request handler for Hono framework
Expand DownExpand Up@@ -99,7 +100,8 @@ export function responseHandler(
}

function updateSpanRouteName(isolationScope: Scope, context: Context): void {
const routeName = `${context.req.method} ${resolveRouteName(context)}`;
const route = resolveRouteName(context);
const routeName = `${context.req.method} ${route}`;
const activeSpan = getActiveSpan();

if (activeSpan) {
Expand All@@ -108,7 +110,10 @@ function updateSpanRouteName(isolationScope: Scope, context: Context): void {

const rootSpan = getRootSpan(activeSpan);
updateSpanName(rootSpan, routeName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

isolationScope.setTransactionName(routeName);
Expand Down
13 changes: 13 additions & 0 deletions packages/hono/test/shared/middlewareHandlers.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { requestHandler, responseHandler } from '../../src/shared/middlewareHandlers';

Expand DownExpand Up@@ -245,6 +246,18 @@ describe('responseHandler', () => {

expect(mockSetTransactionName).toHaveBeenCalledWith('GET /test');
});

it('sets http.route on the root span', () => {
getActiveSpanMock.mockReturnValue(mockRootSpan);

// oxlint-disable-next-line typescript/no-explicit-any
requestHandler(createMockContext(200) as any);

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/test',
});
});
});
});

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import type { NextApiRequest } from 'next';
import type { AugmentedNextApiResponse, NextApiHandler } from '../types';
import { flushSafelyWithTimeout, waitUntil } from '../utils/responseEnd';
import { dropNextjsRootContext, escapeNextjsTracing } from '../utils/tracingUtils';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

export type AugmentedNextApiRequest = NextApiRequest & {
__withSentry_applied__?: boolean;
Expand DownExpand Up@@ -94,6 +94,7 @@ export function wrapApiHandlerWithSentry(apiHandler: NextApiHandler, parameteriz
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: urlObject && !isURLObjectRelative(urlObject) ? urlObject.href : undefined,
[URL_PATH]: urlObject?.pathname,
[HTTP_ROUTE]: parameterizedRoute,
},
},
async span => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { Event } from '@sentry/core';
import { getClient } from '@sentry/core';
import { URL_PATH } from '@sentry/conventions/attributes';
import { getSanitizedRequestUrl } from './urls';

/**
Expand All@@ -20,7 +21,7 @@ export function setUrlProcessingMetadata(event: Event): void {

// Get the route from trace data
const componentRoute = traceData['next.route'] || traceData['http.route'];
const httpTarget = traceData['http.target'] as string | undefined;
const httpTarget = (traceData['http.target'] || traceData[URL_PATH]) as string | undefined;

if (!componentRoute) {
return;
Expand Down
8 changes: 6 additions & 2 deletions packages/nextjs/src/common/wrapRouteHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavi
import type { RouteHandlerContext } from './types';
import { flushSafelyWithTimeout, waitUntil } from './utils/responseEnd';
import { commonObjectToIsolationScope } from './utils/tracingUtils';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js App Router Route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -47,8 +48,11 @@ export function wrapRouteHandlerWithSentry<F extends (...args: any[]) => any>(
edgeRuntimeIsolationScopeOverride = isolationScope;

rootSpan.updateName(`${method} ${parameterizedRoute}`);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'http.server');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[HTTP_ROUTE]: parameterizedRoute,
});
}

return withIsolationScope(
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/src/edge/wrapApiHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import {
import { addHeadersAsAttributes } from '../common/utils/addHeadersAsAttributes';
import { flushSafelyWithTimeout, waitUntil } from '../common/utils/responseEnd';
import type { EdgeRouteHandler } from './types';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js edge route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -75,6 +75,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: rootSpanAttributes[URL_FULL] ?? urlAttributes[URL_FULL],
[URL_PATH]: rootSpanAttributes[URL_PATH] ?? urlAttributes[URL_PATH],
[HTTP_ROUTE]: parameterizedRoute,
...headerAttributes,
});
setCapturedScopesOnSpan(rootSpan, currentScope, isolationScope);
Expand All@@ -92,6 +93,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs.wrap_api_handler',
[HTTP_ROUTE]: parameterizedRoute,
...urlAttributes,
...headerAttributes,
},
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/src/server/enhanceHandleRequestRootSpan.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const cleanRoute = route.replace(/\/route$/, '');
span.setName(`${method} ${cleanRoute}`);
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';
attributes[HTTP_ROUTE] = cleanRoute;
// Preserve next.route in case it did not get hoisted
attributes[ATTR_NEXT_ROUTE] = cleanRoute;
}
Expand All@@ -55,6 +56,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const routeBackfill = attributes[TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL];
if (typeof routeBackfill === 'string' && span.getName() !== 'GET /_app') {
span.setName(`${typeof method === 'string' ? method : 'GET'} ${routeBackfill}`);
attributes[HTTP_ROUTE] = attributes[HTTP_ROUTE] ?? routeBackfill;
}

const middlewareMatch =
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import * as SentryCore from '@sentry/core';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
Expand DownExpand Up@@ -55,6 +55,7 @@ describe('withSentry', () => {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: 'https://dogs.are.great/api/dogs?good=true',
[URL_PATH]: '/api/dogs',
[HTTP_ROUTE]: '/my-parameterized-route',
},
},
expect.any(Function),
Expand Down
53 changes: 51 additions & 2 deletions packages/nextjs/test/edge/withSentryAPI.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
import { afterAll, afterEach, describe, it, vi } from 'vitest';
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { wrapApiHandlerWithSentry } from '../../src/edge';

const origRequest = global.Request;
Expand DownExpand Up@@ -30,7 +33,7 @@ afterAll(() => {
});

afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
});

describe('wrapApiHandlerWithSentry', () => {
Expand All@@ -41,4 +44,50 @@ describe('wrapApiHandlerWithSentry', () => {

await wrappedFunction();
});

it('adds normalized request URL and route attributes to the active root span', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({ data: {} } as any);
const origFunction = vi.fn(() => new Response());
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(origFunction, parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456?good=true'));

expect(rootSpan.updateName).toHaveBeenCalledWith(`POST ${parameterizedRoute}`);
expect(rootSpan.setAttributes).toHaveBeenCalledWith({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: 'https://dogs.are.great/user/123/post/456?good=true',
[URL_PATH]: '/user/123/post/456',
[HTTP_ROUTE]: parameterizedRoute,
});
});

it('replaces a concrete root span route with the parameterized route', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({
data: { [HTTP_ROUTE]: '/user/123/post/456' },
} as any);
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(() => new Response(), parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456'));

expect(rootSpan.setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
[HTTP_ROUTE]: parameterizedRoute,
}),
);
});
});
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { describe, expect, it } from 'vitest';
import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_NAME, ATTR_NEXT_SPAN_TYPE } from '../../src/common/nextSpanAttributes';
Expand DownExpand Up@@ -48,6 +49,7 @@ describe('enhanceHandleRequestRootSpan', () => {
expect(getName()).toBe('GET /api/users/[id]');
expect(span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]).toBe('route');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/users/[id]');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/users/[id]');
});

it('strips trailing /route from app router route handler routes', () => {
Expand All@@ -64,6 +66,7 @@ describe('enhanceHandleRequestRootSpan', () => {

expect(getName()).toBe('POST /api/widgets');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/widgets');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/widgets');
});

it('strips URL query and fragment from the segment name', () => {
Expand DownExpand Up@@ -105,6 +108,7 @@ describe('enhanceHandleRequestRootSpan', () => {
enhanceHandleRequestRootSpan(span);

expect(getName()).toBe('GET /posts/[slug]');
expect(span.attributes[HTTP_ROUTE]).toBe('/posts/[slug]');
});

it('does not apply the backfill for the special GET /_app transaction', () => {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ test('Sends parameterized transaction name to Sentry', async ({ page }) => {

expect(transaction).toBeDefined();
expect(transaction.transaction).toBe('GET user/:id');
expect(transaction.contexts?.trace?.data?.['http.route']).toBe('user/:id');
});

test('Sends form data with action span', async ({ page }) => {
Expand DownExpand Up@@ -271,6 +272,7 @@ test('Sends two linked transactions (server & client) to Sentry', async ({ page
const pageLoadParentSpanId = pageloadTransaction.contexts?.trace?.parent_span_id;

expect(httpServerTransaction.transaction).toBe('GET http://localhost:3030/');
expect(httpServerTransaction.contexts?.trace?.data?.['http.route']).toBeUndefined();
expect(pageloadTransaction.transaction).toBe('/');

expect(httpServerTraceId).toBeDefined();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,7 +42,7 @@ test('should trace orpc server component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/list',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand DownExpand Up@@ -99,7 +99,7 @@ test('should trace orpc client component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/find',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand Down
16 changes: 11 additions & 5 deletions packages/elysia/src/withElysia.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import {
captureException,
Expand DownExpand Up@@ -60,18 +60,24 @@ const instrumentedApps = new WeakSet<Elysia>();
function updateRouteTransactionName(request: Request, method: string, route: string): void {
const transactionName = `${method} ${route}`;

function applyRouteToSpan(span: Span): void {
updateSpanName(span, transactionName);
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

// Try the stored root span first (reliable across async contexts),
// then fall back to getActiveSpan() for cases where async context is preserved.
const rootSpan = rootSpanForRequest.get(request);
if (rootSpan) {
updateSpanName(rootSpan, transactionName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(rootSpan);
} else {
const activeSpan = getActiveSpan();
if (activeSpan) {
const root = getRootSpan(activeSpan);
updateSpanName(root, transactionName);
root.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(root);
}
}

Expand Down
26 changes: 26 additions & 0 deletions packages/elysia/test/withElysia.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import type { ErrorContext } from 'elysia';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

Expand DownExpand Up@@ -32,6 +33,12 @@ const mockGetIsolationScope = vi.fn(() => ({
const mockGetClient = vi.fn(() => ({
on: vi.fn(),
}));
const mockRootSpan = {
setAttributes: vi.fn(),
updateName: vi.fn(),
};
const mockGetActiveSpan = vi.fn();
const mockGetRootSpan = vi.fn(() => mockRootSpan);
const mockGetTraceData = vi.fn(() => ({
'sentry-trace': 'abc123-def456-1',
baggage: 'sentry-environment=test,sentry-trace_id=abc123',
Expand All@@ -43,8 +50,10 @@ vi.mock('@sentry/core', async importActual => {
return {
...actual,
captureException: (...args: unknown[]) => mockCaptureException(...args),
getActiveSpan: () => mockGetActiveSpan(),
getIsolationScope: () => mockGetIsolationScope(),
getClient: () => mockGetClient(),
getRootSpan: () => mockGetRootSpan(),
getTraceData: () => mockGetTraceData(),
};
});
Expand DownExpand Up@@ -88,6 +97,23 @@ describe('withElysia', () => {
expect(headers['baggage']).toBe('sentry-environment=test,sentry-trace_id=abc123');
});

it('sets the matched route on the root span', () => {
mockGetActiveSpan.mockReturnValueOnce(mockRootSpan);
// @ts-expect-error - mock app
withElysia(mockApp);

onAfterHandleHandler({
route: '/users/:id',
request: new Request('https://example.com/users/42', { method: 'GET' }),
set: { headers: {} },
});

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/users/:id',
});
});

it('does not set headers when trace data is empty', () => {
mockGetTraceData.mockReturnValueOnce({});
// @ts-expect-error - mock app
Expand Down
3 changes: 2 additions & 1 deletion packages/hono/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -92,7 +92,8 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"@sentry/conventions": "^0.16.0"
},
"peerDependencies": {
"@cloudflare/workers-types": "^4.x",
Expand Down
9 changes: 7 additions & 2 deletions packages/hono/src/shared/middlewareHandlers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import { defaultShouldHandleError } from './defaultShouldHandleError';
import { resolveRouteName } from './resolveRouteName';
import { type SentryHonoMiddlewareOptions } from '../shared/types';
import { type GetConnInfo } from 'hono/conninfo';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Request handler for Hono framework
Expand DownExpand Up@@ -99,7 +100,8 @@ export function responseHandler(
}

function updateSpanRouteName(isolationScope: Scope, context: Context): void {
const routeName = `${context.req.method} ${resolveRouteName(context)}`;
const route = resolveRouteName(context);
const routeName = `${context.req.method} ${route}`;
const activeSpan = getActiveSpan();

if (activeSpan) {
Expand All@@ -108,7 +110,10 @@ function updateSpanRouteName(isolationScope: Scope, context: Context): void {

const rootSpan = getRootSpan(activeSpan);
updateSpanName(rootSpan, routeName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

isolationScope.setTransactionName(routeName);
Expand Down
13 changes: 13 additions & 0 deletions packages/hono/test/shared/middlewareHandlers.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { requestHandler, responseHandler } from '../../src/shared/middlewareHandlers';

Expand DownExpand Up@@ -245,6 +246,18 @@ describe('responseHandler', () => {

expect(mockSetTransactionName).toHaveBeenCalledWith('GET /test');
});

it('sets http.route on the root span', () => {
getActiveSpanMock.mockReturnValue(mockRootSpan);

// oxlint-disable-next-line typescript/no-explicit-any
requestHandler(createMockContext(200) as any);

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/test',
});
});
});
});

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import type { NextApiRequest } from 'next';
import type { AugmentedNextApiResponse, NextApiHandler } from '../types';
import { flushSafelyWithTimeout, waitUntil } from '../utils/responseEnd';
import { dropNextjsRootContext, escapeNextjsTracing } from '../utils/tracingUtils';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

export type AugmentedNextApiRequest = NextApiRequest & {
__withSentry_applied__?: boolean;
Expand DownExpand Up@@ -94,6 +94,7 @@ export function wrapApiHandlerWithSentry(apiHandler: NextApiHandler, parameteriz
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: urlObject && !isURLObjectRelative(urlObject) ? urlObject.href : undefined,
[URL_PATH]: urlObject?.pathname,
[HTTP_ROUTE]: parameterizedRoute,
},
},
async span => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { Event } from '@sentry/core';
import { getClient } from '@sentry/core';
import { URL_PATH } from '@sentry/conventions/attributes';
import { getSanitizedRequestUrl } from './urls';

/**
Expand All@@ -20,7 +21,7 @@ export function setUrlProcessingMetadata(event: Event): void {

// Get the route from trace data
const componentRoute = traceData['next.route'] || traceData['http.route'];
const httpTarget = traceData['http.target'] as string | undefined;
const httpTarget = (traceData['http.target'] || traceData[URL_PATH]) as string | undefined;

if (!componentRoute) {
return;
Expand Down
8 changes: 6 additions & 2 deletions packages/nextjs/src/common/wrapRouteHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavi
import type { RouteHandlerContext } from './types';
import { flushSafelyWithTimeout, waitUntil } from './utils/responseEnd';
import { commonObjectToIsolationScope } from './utils/tracingUtils';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js App Router Route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -47,8 +48,11 @@ export function wrapRouteHandlerWithSentry<F extends (...args: any[]) => any>(
edgeRuntimeIsolationScopeOverride = isolationScope;

rootSpan.updateName(`${method} ${parameterizedRoute}`);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'http.server');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[HTTP_ROUTE]: parameterizedRoute,
});
}

return withIsolationScope(
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/src/edge/wrapApiHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import {
import { addHeadersAsAttributes } from '../common/utils/addHeadersAsAttributes';
import { flushSafelyWithTimeout, waitUntil } from '../common/utils/responseEnd';
import type { EdgeRouteHandler } from './types';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js edge route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -75,6 +75,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: rootSpanAttributes[URL_FULL] ?? urlAttributes[URL_FULL],
[URL_PATH]: rootSpanAttributes[URL_PATH] ?? urlAttributes[URL_PATH],
[HTTP_ROUTE]: parameterizedRoute,
...headerAttributes,
});
setCapturedScopesOnSpan(rootSpan, currentScope, isolationScope);
Expand All@@ -92,6 +93,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs.wrap_api_handler',
[HTTP_ROUTE]: parameterizedRoute,
...urlAttributes,
...headerAttributes,
},
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/src/server/enhanceHandleRequestRootSpan.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const cleanRoute = route.replace(/\/route$/, '');
span.setName(`${method} ${cleanRoute}`);
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';
attributes[HTTP_ROUTE] = cleanRoute;
// Preserve next.route in case it did not get hoisted
attributes[ATTR_NEXT_ROUTE] = cleanRoute;
}
Expand All@@ -55,6 +56,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const routeBackfill = attributes[TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL];
if (typeof routeBackfill === 'string' && span.getName() !== 'GET /_app') {
span.setName(`${typeof method === 'string' ? method : 'GET'} ${routeBackfill}`);
attributes[HTTP_ROUTE] = attributes[HTTP_ROUTE] ?? routeBackfill;
}

const middlewareMatch =
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import * as SentryCore from '@sentry/core';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
Expand DownExpand Up@@ -55,6 +55,7 @@ describe('withSentry', () => {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: 'https://dogs.are.great/api/dogs?good=true',
[URL_PATH]: '/api/dogs',
[HTTP_ROUTE]: '/my-parameterized-route',
},
},
expect.any(Function),
Expand Down
53 changes: 51 additions & 2 deletions packages/nextjs/test/edge/withSentryAPI.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
import { afterAll, afterEach, describe, it, vi } from 'vitest';
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { wrapApiHandlerWithSentry } from '../../src/edge';

const origRequest = global.Request;
Expand DownExpand Up@@ -30,7 +33,7 @@ afterAll(() => {
});

afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
});

describe('wrapApiHandlerWithSentry', () => {
Expand All@@ -41,4 +44,50 @@ describe('wrapApiHandlerWithSentry', () => {

await wrappedFunction();
});

it('adds normalized request URL and route attributes to the active root span', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({ data: {} } as any);
const origFunction = vi.fn(() => new Response());
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(origFunction, parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456?good=true'));

expect(rootSpan.updateName).toHaveBeenCalledWith(`POST ${parameterizedRoute}`);
expect(rootSpan.setAttributes).toHaveBeenCalledWith({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: 'https://dogs.are.great/user/123/post/456?good=true',
[URL_PATH]: '/user/123/post/456',
[HTTP_ROUTE]: parameterizedRoute,
});
});

it('replaces a concrete root span route with the parameterized route', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({
data: { [HTTP_ROUTE]: '/user/123/post/456' },
} as any);
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(() => new Response(), parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456'));

expect(rootSpan.setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
[HTTP_ROUTE]: parameterizedRoute,
}),
);
});
});
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { describe, expect, it } from 'vitest';
import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_NAME, ATTR_NEXT_SPAN_TYPE } from '../../src/common/nextSpanAttributes';
Expand DownExpand Up@@ -48,6 +49,7 @@ describe('enhanceHandleRequestRootSpan', () => {
expect(getName()).toBe('GET /api/users/[id]');
expect(span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]).toBe('route');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/users/[id]');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/users/[id]');
});

it('strips trailing /route from app router route handler routes', () => {
Expand All@@ -64,6 +66,7 @@ describe('enhanceHandleRequestRootSpan', () => {

expect(getName()).toBe('POST /api/widgets');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/widgets');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/widgets');
});

it('strips URL query and fragment from the segment name', () => {
Expand DownExpand Up@@ -105,6 +108,7 @@ describe('enhanceHandleRequestRootSpan', () => {
enhanceHandleRequestRootSpan(span);

expect(getName()).toBe('GET /posts/[slug]');
expect(span.attributes[HTTP_ROUTE]).toBe('/posts/[slug]');
});

it('does not apply the backfill for the special GET /_app transaction', () => {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ test('Sends parameterized transaction name to Sentry', async ({ page }) => {

expect(transaction).toBeDefined();
expect(transaction.transaction).toBe('GET user/:id');
expect(transaction.contexts?.trace?.data?.['http.route']).toBe('user/:id');
});

test('Sends form data with action span', async ({ page }) => {
Expand DownExpand Up@@ -271,6 +272,7 @@ test('Sends two linked transactions (server & client) to Sentry', async ({ page
const pageLoadParentSpanId = pageloadTransaction.contexts?.trace?.parent_span_id;

expect(httpServerTransaction.transaction).toBe('GET http://localhost:3030/');
expect(httpServerTransaction.contexts?.trace?.data?.['http.route']).toBeUndefined();
expect(pageloadTransaction.transaction).toBe('/');

expect(httpServerTraceId).toBeDefined();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,7 +42,7 @@ test('should trace orpc server component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/list',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand DownExpand Up@@ -99,7 +99,7 @@ test('should trace orpc client component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/find',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand Down
16 changes: 11 additions & 5 deletions packages/elysia/src/withElysia.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import {
captureException,
Expand DownExpand Up@@ -60,18 +60,24 @@ const instrumentedApps = new WeakSet<Elysia>();
function updateRouteTransactionName(request: Request, method: string, route: string): void {
const transactionName = `${method} ${route}`;

function applyRouteToSpan(span: Span): void {
updateSpanName(span, transactionName);
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

// Try the stored root span first (reliable across async contexts),
// then fall back to getActiveSpan() for cases where async context is preserved.
const rootSpan = rootSpanForRequest.get(request);
if (rootSpan) {
updateSpanName(rootSpan, transactionName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(rootSpan);
} else {
const activeSpan = getActiveSpan();
if (activeSpan) {
const root = getRootSpan(activeSpan);
updateSpanName(root, transactionName);
root.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(root);
}
}

Expand Down
26 changes: 26 additions & 0 deletions packages/elysia/test/withElysia.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import type { ErrorContext } from 'elysia';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

Expand DownExpand Up@@ -32,6 +33,12 @@ const mockGetIsolationScope = vi.fn(() => ({
const mockGetClient = vi.fn(() => ({
on: vi.fn(),
}));
const mockRootSpan = {
setAttributes: vi.fn(),
updateName: vi.fn(),
};
const mockGetActiveSpan = vi.fn();
const mockGetRootSpan = vi.fn(() => mockRootSpan);
const mockGetTraceData = vi.fn(() => ({
'sentry-trace': 'abc123-def456-1',
baggage: 'sentry-environment=test,sentry-trace_id=abc123',
Expand All@@ -43,8 +50,10 @@ vi.mock('@sentry/core', async importActual => {
return {
...actual,
captureException: (...args: unknown[]) => mockCaptureException(...args),
getActiveSpan: () => mockGetActiveSpan(),
getIsolationScope: () => mockGetIsolationScope(),
getClient: () => mockGetClient(),
getRootSpan: () => mockGetRootSpan(),
getTraceData: () => mockGetTraceData(),
};
});
Expand DownExpand Up@@ -88,6 +97,23 @@ describe('withElysia', () => {
expect(headers['baggage']).toBe('sentry-environment=test,sentry-trace_id=abc123');
});

it('sets the matched route on the root span', () => {
mockGetActiveSpan.mockReturnValueOnce(mockRootSpan);
// @ts-expect-error - mock app
withElysia(mockApp);

onAfterHandleHandler({
route: '/users/:id',
request: new Request('https://example.com/users/42', { method: 'GET' }),
set: { headers: {} },
});

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/users/:id',
});
});

it('does not set headers when trace data is empty', () => {
mockGetTraceData.mockReturnValueOnce({});
// @ts-expect-error - mock app
Expand Down
3 changes: 2 additions & 1 deletion packages/hono/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -92,7 +92,8 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"@sentry/conventions": "^0.16.0"
},
"peerDependencies": {
"@cloudflare/workers-types": "^4.x",
Expand Down
9 changes: 7 additions & 2 deletions packages/hono/src/shared/middlewareHandlers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import { defaultShouldHandleError } from './defaultShouldHandleError';
import { resolveRouteName } from './resolveRouteName';
import { type SentryHonoMiddlewareOptions } from '../shared/types';
import { type GetConnInfo } from 'hono/conninfo';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Request handler for Hono framework
Expand DownExpand Up@@ -99,7 +100,8 @@ export function responseHandler(
}

function updateSpanRouteName(isolationScope: Scope, context: Context): void {
const routeName = `${context.req.method} ${resolveRouteName(context)}`;
const route = resolveRouteName(context);
const routeName = `${context.req.method} ${route}`;
const activeSpan = getActiveSpan();

if (activeSpan) {
Expand All@@ -108,7 +110,10 @@ function updateSpanRouteName(isolationScope: Scope, context: Context): void {

const rootSpan = getRootSpan(activeSpan);
updateSpanName(rootSpan, routeName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

isolationScope.setTransactionName(routeName);
Expand Down
13 changes: 13 additions & 0 deletions packages/hono/test/shared/middlewareHandlers.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { requestHandler, responseHandler } from '../../src/shared/middlewareHandlers';

Expand DownExpand Up@@ -245,6 +246,18 @@ describe('responseHandler', () => {

expect(mockSetTransactionName).toHaveBeenCalledWith('GET /test');
});

it('sets http.route on the root span', () => {
getActiveSpanMock.mockReturnValue(mockRootSpan);

// oxlint-disable-next-line typescript/no-explicit-any
requestHandler(createMockContext(200) as any);

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/test',
});
});
});
});

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import type { NextApiRequest } from 'next';
import type { AugmentedNextApiResponse, NextApiHandler } from '../types';
import { flushSafelyWithTimeout, waitUntil } from '../utils/responseEnd';
import { dropNextjsRootContext, escapeNextjsTracing } from '../utils/tracingUtils';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

export type AugmentedNextApiRequest = NextApiRequest & {
__withSentry_applied__?: boolean;
Expand DownExpand Up@@ -94,6 +94,7 @@ export function wrapApiHandlerWithSentry(apiHandler: NextApiHandler, parameteriz
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: urlObject && !isURLObjectRelative(urlObject) ? urlObject.href : undefined,
[URL_PATH]: urlObject?.pathname,
[HTTP_ROUTE]: parameterizedRoute,
},
},
async span => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { Event } from '@sentry/core';
import { getClient } from '@sentry/core';
import { URL_PATH } from '@sentry/conventions/attributes';
import { getSanitizedRequestUrl } from './urls';

/**
Expand All@@ -20,7 +21,7 @@ export function setUrlProcessingMetadata(event: Event): void {

// Get the route from trace data
const componentRoute = traceData['next.route'] || traceData['http.route'];
const httpTarget = traceData['http.target'] as string | undefined;
const httpTarget = (traceData['http.target'] || traceData[URL_PATH]) as string | undefined;

if (!componentRoute) {
return;
Expand Down
8 changes: 6 additions & 2 deletions packages/nextjs/src/common/wrapRouteHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavi
import type { RouteHandlerContext } from './types';
import { flushSafelyWithTimeout, waitUntil } from './utils/responseEnd';
import { commonObjectToIsolationScope } from './utils/tracingUtils';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js App Router Route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -47,8 +48,11 @@ export function wrapRouteHandlerWithSentry<F extends (...args: any[]) => any>(
edgeRuntimeIsolationScopeOverride = isolationScope;

rootSpan.updateName(`${method} ${parameterizedRoute}`);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'http.server');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[HTTP_ROUTE]: parameterizedRoute,
});
}

return withIsolationScope(
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/src/edge/wrapApiHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import {
import { addHeadersAsAttributes } from '../common/utils/addHeadersAsAttributes';
import { flushSafelyWithTimeout, waitUntil } from '../common/utils/responseEnd';
import type { EdgeRouteHandler } from './types';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js edge route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -75,6 +75,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: rootSpanAttributes[URL_FULL] ?? urlAttributes[URL_FULL],
[URL_PATH]: rootSpanAttributes[URL_PATH] ?? urlAttributes[URL_PATH],
[HTTP_ROUTE]: parameterizedRoute,
...headerAttributes,
});
setCapturedScopesOnSpan(rootSpan, currentScope, isolationScope);
Expand All@@ -92,6 +93,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs.wrap_api_handler',
[HTTP_ROUTE]: parameterizedRoute,
...urlAttributes,
...headerAttributes,
},
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/src/server/enhanceHandleRequestRootSpan.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const cleanRoute = route.replace(/\/route$/, '');
span.setName(`${method} ${cleanRoute}`);
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';
attributes[HTTP_ROUTE] = cleanRoute;
// Preserve next.route in case it did not get hoisted
attributes[ATTR_NEXT_ROUTE] = cleanRoute;
}
Expand All@@ -55,6 +56,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const routeBackfill = attributes[TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL];
if (typeof routeBackfill === 'string' && span.getName() !== 'GET /_app') {
span.setName(`${typeof method === 'string' ? method : 'GET'} ${routeBackfill}`);
attributes[HTTP_ROUTE] = attributes[HTTP_ROUTE] ?? routeBackfill;
}

const middlewareMatch =
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import * as SentryCore from '@sentry/core';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
Expand DownExpand Up@@ -55,6 +55,7 @@ describe('withSentry', () => {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: 'https://dogs.are.great/api/dogs?good=true',
[URL_PATH]: '/api/dogs',
[HTTP_ROUTE]: '/my-parameterized-route',
},
},
expect.any(Function),
Expand Down
53 changes: 51 additions & 2 deletions packages/nextjs/test/edge/withSentryAPI.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
import { afterAll, afterEach, describe, it, vi } from 'vitest';
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { wrapApiHandlerWithSentry } from '../../src/edge';

const origRequest = global.Request;
Expand DownExpand Up@@ -30,7 +33,7 @@ afterAll(() => {
});

afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
});

describe('wrapApiHandlerWithSentry', () => {
Expand All@@ -41,4 +44,50 @@ describe('wrapApiHandlerWithSentry', () => {

await wrappedFunction();
});

it('adds normalized request URL and route attributes to the active root span', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({ data: {} } as any);
const origFunction = vi.fn(() => new Response());
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(origFunction, parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456?good=true'));

expect(rootSpan.updateName).toHaveBeenCalledWith(`POST ${parameterizedRoute}`);
expect(rootSpan.setAttributes).toHaveBeenCalledWith({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: 'https://dogs.are.great/user/123/post/456?good=true',
[URL_PATH]: '/user/123/post/456',
[HTTP_ROUTE]: parameterizedRoute,
});
});

it('replaces a concrete root span route with the parameterized route', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({
data: { [HTTP_ROUTE]: '/user/123/post/456' },
} as any);
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(() => new Response(), parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456'));

expect(rootSpan.setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
[HTTP_ROUTE]: parameterizedRoute,
}),
);
});
});
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { describe, expect, it } from 'vitest';
import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_NAME, ATTR_NEXT_SPAN_TYPE } from '../../src/common/nextSpanAttributes';
Expand DownExpand Up@@ -48,6 +49,7 @@ describe('enhanceHandleRequestRootSpan', () => {
expect(getName()).toBe('GET /api/users/[id]');
expect(span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]).toBe('route');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/users/[id]');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/users/[id]');
});

it('strips trailing /route from app router route handler routes', () => {
Expand All@@ -64,6 +66,7 @@ describe('enhanceHandleRequestRootSpan', () => {

expect(getName()).toBe('POST /api/widgets');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/widgets');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/widgets');
});

it('strips URL query and fragment from the segment name', () => {
Expand DownExpand Up@@ -105,6 +108,7 @@ describe('enhanceHandleRequestRootSpan', () => {
enhanceHandleRequestRootSpan(span);

expect(getName()).toBe('GET /posts/[slug]');
expect(span.attributes[HTTP_ROUTE]).toBe('/posts/[slug]');
});

it('does not apply the backfill for the special GET /_app transaction', () => {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ test('Sends parameterized transaction name to Sentry', async ({ page }) => {

expect(transaction).toBeDefined();
expect(transaction.transaction).toBe('GET user/:id');
expect(transaction.contexts?.trace?.data?.['http.route']).toBe('user/:id');
});

test('Sends form data with action span', async ({ page }) => {
Expand DownExpand Up@@ -271,6 +272,7 @@ test('Sends two linked transactions (server & client) to Sentry', async ({ page
const pageLoadParentSpanId = pageloadTransaction.contexts?.trace?.parent_span_id;

expect(httpServerTransaction.transaction).toBe('GET http://localhost:3030/');
expect(httpServerTransaction.contexts?.trace?.data?.['http.route']).toBeUndefined();
expect(pageloadTransaction.transaction).toBe('/');

expect(httpServerTraceId).toBeDefined();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,7 +42,7 @@ test('should trace orpc server component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/list',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand DownExpand Up@@ -99,7 +99,7 @@ test('should trace orpc client component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/find',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand Down
16 changes: 11 additions & 5 deletions packages/elysia/src/withElysia.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import {
captureException,
Expand DownExpand Up@@ -60,18 +60,24 @@ const instrumentedApps = new WeakSet<Elysia>();
function updateRouteTransactionName(request: Request, method: string, route: string): void {
const transactionName = `${method} ${route}`;

function applyRouteToSpan(span: Span): void {
updateSpanName(span, transactionName);
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

// Try the stored root span first (reliable across async contexts),
// then fall back to getActiveSpan() for cases where async context is preserved.
const rootSpan = rootSpanForRequest.get(request);
if (rootSpan) {
updateSpanName(rootSpan, transactionName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(rootSpan);
} else {
const activeSpan = getActiveSpan();
if (activeSpan) {
const root = getRootSpan(activeSpan);
updateSpanName(root, transactionName);
root.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(root);
}
}

Expand Down
26 changes: 26 additions & 0 deletions packages/elysia/test/withElysia.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import type { ErrorContext } from 'elysia';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

Expand DownExpand Up@@ -32,6 +33,12 @@ const mockGetIsolationScope = vi.fn(() => ({
const mockGetClient = vi.fn(() => ({
on: vi.fn(),
}));
const mockRootSpan = {
setAttributes: vi.fn(),
updateName: vi.fn(),
};
const mockGetActiveSpan = vi.fn();
const mockGetRootSpan = vi.fn(() => mockRootSpan);
const mockGetTraceData = vi.fn(() => ({
'sentry-trace': 'abc123-def456-1',
baggage: 'sentry-environment=test,sentry-trace_id=abc123',
Expand All@@ -43,8 +50,10 @@ vi.mock('@sentry/core', async importActual => {
return {
...actual,
captureException: (...args: unknown[]) => mockCaptureException(...args),
getActiveSpan: () => mockGetActiveSpan(),
getIsolationScope: () => mockGetIsolationScope(),
getClient: () => mockGetClient(),
getRootSpan: () => mockGetRootSpan(),
getTraceData: () => mockGetTraceData(),
};
});
Expand DownExpand Up@@ -88,6 +97,23 @@ describe('withElysia', () => {
expect(headers['baggage']).toBe('sentry-environment=test,sentry-trace_id=abc123');
});

it('sets the matched route on the root span', () => {
mockGetActiveSpan.mockReturnValueOnce(mockRootSpan);
// @ts-expect-error - mock app
withElysia(mockApp);

onAfterHandleHandler({
route: '/users/:id',
request: new Request('https://example.com/users/42', { method: 'GET' }),
set: { headers: {} },
});

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/users/:id',
});
});

it('does not set headers when trace data is empty', () => {
mockGetTraceData.mockReturnValueOnce({});
// @ts-expect-error - mock app
Expand Down
3 changes: 2 additions & 1 deletion packages/hono/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -92,7 +92,8 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"@sentry/conventions": "^0.16.0"
},
"peerDependencies": {
"@cloudflare/workers-types": "^4.x",
Expand Down
9 changes: 7 additions & 2 deletions packages/hono/src/shared/middlewareHandlers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import { defaultShouldHandleError } from './defaultShouldHandleError';
import { resolveRouteName } from './resolveRouteName';
import { type SentryHonoMiddlewareOptions } from '../shared/types';
import { type GetConnInfo } from 'hono/conninfo';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Request handler for Hono framework
Expand DownExpand Up@@ -99,7 +100,8 @@ export function responseHandler(
}

function updateSpanRouteName(isolationScope: Scope, context: Context): void {
const routeName = `${context.req.method} ${resolveRouteName(context)}`;
const route = resolveRouteName(context);
const routeName = `${context.req.method} ${route}`;
const activeSpan = getActiveSpan();

if (activeSpan) {
Expand All@@ -108,7 +110,10 @@ function updateSpanRouteName(isolationScope: Scope, context: Context): void {

const rootSpan = getRootSpan(activeSpan);
updateSpanName(rootSpan, routeName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

isolationScope.setTransactionName(routeName);
Expand Down
13 changes: 13 additions & 0 deletions packages/hono/test/shared/middlewareHandlers.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { requestHandler, responseHandler } from '../../src/shared/middlewareHandlers';

Expand DownExpand Up@@ -245,6 +246,18 @@ describe('responseHandler', () => {

expect(mockSetTransactionName).toHaveBeenCalledWith('GET /test');
});

it('sets http.route on the root span', () => {
getActiveSpanMock.mockReturnValue(mockRootSpan);

// oxlint-disable-next-line typescript/no-explicit-any
requestHandler(createMockContext(200) as any);

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/test',
});
});
});
});

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import type { NextApiRequest } from 'next';
import type { AugmentedNextApiResponse, NextApiHandler } from '../types';
import { flushSafelyWithTimeout, waitUntil } from '../utils/responseEnd';
import { dropNextjsRootContext, escapeNextjsTracing } from '../utils/tracingUtils';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

export type AugmentedNextApiRequest = NextApiRequest & {
__withSentry_applied__?: boolean;
Expand DownExpand Up@@ -94,6 +94,7 @@ export function wrapApiHandlerWithSentry(apiHandler: NextApiHandler, parameteriz
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: urlObject && !isURLObjectRelative(urlObject) ? urlObject.href : undefined,
[URL_PATH]: urlObject?.pathname,
[HTTP_ROUTE]: parameterizedRoute,
},
},
async span => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { Event } from '@sentry/core';
import { getClient } from '@sentry/core';
import { URL_PATH } from '@sentry/conventions/attributes';
import { getSanitizedRequestUrl } from './urls';

/**
Expand All@@ -20,7 +21,7 @@ export function setUrlProcessingMetadata(event: Event): void {

// Get the route from trace data
const componentRoute = traceData['next.route'] || traceData['http.route'];
const httpTarget = traceData['http.target'] as string | undefined;
const httpTarget = (traceData['http.target'] || traceData[URL_PATH]) as string | undefined;

if (!componentRoute) {
return;
Expand Down
8 changes: 6 additions & 2 deletions packages/nextjs/src/common/wrapRouteHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavi
import type { RouteHandlerContext } from './types';
import { flushSafelyWithTimeout, waitUntil } from './utils/responseEnd';
import { commonObjectToIsolationScope } from './utils/tracingUtils';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js App Router Route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -47,8 +48,11 @@ export function wrapRouteHandlerWithSentry<F extends (...args: any[]) => any>(
edgeRuntimeIsolationScopeOverride = isolationScope;

rootSpan.updateName(`${method} ${parameterizedRoute}`);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'http.server');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[HTTP_ROUTE]: parameterizedRoute,
});
}

return withIsolationScope(
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/src/edge/wrapApiHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import {
import { addHeadersAsAttributes } from '../common/utils/addHeadersAsAttributes';
import { flushSafelyWithTimeout, waitUntil } from '../common/utils/responseEnd';
import type { EdgeRouteHandler } from './types';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js edge route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -75,6 +75,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: rootSpanAttributes[URL_FULL] ?? urlAttributes[URL_FULL],
[URL_PATH]: rootSpanAttributes[URL_PATH] ?? urlAttributes[URL_PATH],
[HTTP_ROUTE]: parameterizedRoute,
...headerAttributes,
});
setCapturedScopesOnSpan(rootSpan, currentScope, isolationScope);
Expand All@@ -92,6 +93,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs.wrap_api_handler',
[HTTP_ROUTE]: parameterizedRoute,
...urlAttributes,
...headerAttributes,
},
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/src/server/enhanceHandleRequestRootSpan.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const cleanRoute = route.replace(/\/route$/, '');
span.setName(`${method} ${cleanRoute}`);
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';
attributes[HTTP_ROUTE] = cleanRoute;
// Preserve next.route in case it did not get hoisted
attributes[ATTR_NEXT_ROUTE] = cleanRoute;
}
Expand All@@ -55,6 +56,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const routeBackfill = attributes[TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL];
if (typeof routeBackfill === 'string' && span.getName() !== 'GET /_app') {
span.setName(`${typeof method === 'string' ? method : 'GET'} ${routeBackfill}`);
attributes[HTTP_ROUTE] = attributes[HTTP_ROUTE] ?? routeBackfill;
}

const middlewareMatch =
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import * as SentryCore from '@sentry/core';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
Expand DownExpand Up@@ -55,6 +55,7 @@ describe('withSentry', () => {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: 'https://dogs.are.great/api/dogs?good=true',
[URL_PATH]: '/api/dogs',
[HTTP_ROUTE]: '/my-parameterized-route',
},
},
expect.any(Function),
Expand Down
53 changes: 51 additions & 2 deletions packages/nextjs/test/edge/withSentryAPI.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
import { afterAll, afterEach, describe, it, vi } from 'vitest';
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { wrapApiHandlerWithSentry } from '../../src/edge';

const origRequest = global.Request;
Expand DownExpand Up@@ -30,7 +33,7 @@ afterAll(() => {
});

afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
});

describe('wrapApiHandlerWithSentry', () => {
Expand All@@ -41,4 +44,50 @@ describe('wrapApiHandlerWithSentry', () => {

await wrappedFunction();
});

it('adds normalized request URL and route attributes to the active root span', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({ data: {} } as any);
const origFunction = vi.fn(() => new Response());
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(origFunction, parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456?good=true'));

expect(rootSpan.updateName).toHaveBeenCalledWith(`POST ${parameterizedRoute}`);
expect(rootSpan.setAttributes).toHaveBeenCalledWith({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: 'https://dogs.are.great/user/123/post/456?good=true',
[URL_PATH]: '/user/123/post/456',
[HTTP_ROUTE]: parameterizedRoute,
});
});

it('replaces a concrete root span route with the parameterized route', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({
data: { [HTTP_ROUTE]: '/user/123/post/456' },
} as any);
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(() => new Response(), parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456'));

expect(rootSpan.setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
[HTTP_ROUTE]: parameterizedRoute,
}),
);
});
});
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { describe, expect, it } from 'vitest';
import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_NAME, ATTR_NEXT_SPAN_TYPE } from '../../src/common/nextSpanAttributes';
Expand DownExpand Up@@ -48,6 +49,7 @@ describe('enhanceHandleRequestRootSpan', () => {
expect(getName()).toBe('GET /api/users/[id]');
expect(span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]).toBe('route');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/users/[id]');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/users/[id]');
});

it('strips trailing /route from app router route handler routes', () => {
Expand All@@ -64,6 +66,7 @@ describe('enhanceHandleRequestRootSpan', () => {

expect(getName()).toBe('POST /api/widgets');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/widgets');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/widgets');
});

it('strips URL query and fragment from the segment name', () => {
Expand DownExpand Up@@ -105,6 +108,7 @@ describe('enhanceHandleRequestRootSpan', () => {
enhanceHandleRequestRootSpan(span);

expect(getName()).toBe('GET /posts/[slug]');
expect(span.attributes[HTTP_ROUTE]).toBe('/posts/[slug]');
});

it('does not apply the backfill for the special GET /_app transaction', () => {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ test('Sends parameterized transaction name to Sentry', async ({ page }) => {

expect(transaction).toBeDefined();
expect(transaction.transaction).toBe('GET user/:id');
expect(transaction.contexts?.trace?.data?.['http.route']).toBe('user/:id');
});

test('Sends form data with action span', async ({ page }) => {
Expand DownExpand Up@@ -271,6 +272,7 @@ test('Sends two linked transactions (server & client) to Sentry', async ({ page
const pageLoadParentSpanId = pageloadTransaction.contexts?.trace?.parent_span_id;

expect(httpServerTransaction.transaction).toBe('GET http://localhost:3030/');
expect(httpServerTransaction.contexts?.trace?.data?.['http.route']).toBeUndefined();
expect(pageloadTransaction.transaction).toBe('/');

expect(httpServerTraceId).toBeDefined();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,7 +42,7 @@ test('should trace orpc server component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/list',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand DownExpand Up@@ -99,7 +99,7 @@ test('should trace orpc client component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/find',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand Down
16 changes: 11 additions & 5 deletions packages/elysia/src/withElysia.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import {
captureException,
Expand DownExpand Up@@ -60,18 +60,24 @@ const instrumentedApps = new WeakSet<Elysia>();
function updateRouteTransactionName(request: Request, method: string, route: string): void {
const transactionName = `${method} ${route}`;

function applyRouteToSpan(span: Span): void {
updateSpanName(span, transactionName);
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

// Try the stored root span first (reliable across async contexts),
// then fall back to getActiveSpan() for cases where async context is preserved.
const rootSpan = rootSpanForRequest.get(request);
if (rootSpan) {
updateSpanName(rootSpan, transactionName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(rootSpan);
} else {
const activeSpan = getActiveSpan();
if (activeSpan) {
const root = getRootSpan(activeSpan);
updateSpanName(root, transactionName);
root.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(root);
}
}

Expand Down
26 changes: 26 additions & 0 deletions packages/elysia/test/withElysia.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import type { ErrorContext } from 'elysia';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

Expand DownExpand Up@@ -32,6 +33,12 @@ const mockGetIsolationScope = vi.fn(() => ({
const mockGetClient = vi.fn(() => ({
on: vi.fn(),
}));
const mockRootSpan = {
setAttributes: vi.fn(),
updateName: vi.fn(),
};
const mockGetActiveSpan = vi.fn();
const mockGetRootSpan = vi.fn(() => mockRootSpan);
const mockGetTraceData = vi.fn(() => ({
'sentry-trace': 'abc123-def456-1',
baggage: 'sentry-environment=test,sentry-trace_id=abc123',
Expand All@@ -43,8 +50,10 @@ vi.mock('@sentry/core', async importActual => {
return {
...actual,
captureException: (...args: unknown[]) => mockCaptureException(...args),
getActiveSpan: () => mockGetActiveSpan(),
getIsolationScope: () => mockGetIsolationScope(),
getClient: () => mockGetClient(),
getRootSpan: () => mockGetRootSpan(),
getTraceData: () => mockGetTraceData(),
};
});
Expand DownExpand Up@@ -88,6 +97,23 @@ describe('withElysia', () => {
expect(headers['baggage']).toBe('sentry-environment=test,sentry-trace_id=abc123');
});

it('sets the matched route on the root span', () => {
mockGetActiveSpan.mockReturnValueOnce(mockRootSpan);
// @ts-expect-error - mock app
withElysia(mockApp);

onAfterHandleHandler({
route: '/users/:id',
request: new Request('https://example.com/users/42', { method: 'GET' }),
set: { headers: {} },
});

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/users/:id',
});
});

it('does not set headers when trace data is empty', () => {
mockGetTraceData.mockReturnValueOnce({});
// @ts-expect-error - mock app
Expand Down
3 changes: 2 additions & 1 deletion packages/hono/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -92,7 +92,8 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"@sentry/conventions": "^0.16.0"
},
"peerDependencies": {
"@cloudflare/workers-types": "^4.x",
Expand Down
9 changes: 7 additions & 2 deletions packages/hono/src/shared/middlewareHandlers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import { defaultShouldHandleError } from './defaultShouldHandleError';
import { resolveRouteName } from './resolveRouteName';
import { type SentryHonoMiddlewareOptions } from '../shared/types';
import { type GetConnInfo } from 'hono/conninfo';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Request handler for Hono framework
Expand DownExpand Up@@ -99,7 +100,8 @@ export function responseHandler(
}

function updateSpanRouteName(isolationScope: Scope, context: Context): void {
const routeName = `${context.req.method} ${resolveRouteName(context)}`;
const route = resolveRouteName(context);
const routeName = `${context.req.method} ${route}`;
const activeSpan = getActiveSpan();

if (activeSpan) {
Expand All@@ -108,7 +110,10 @@ function updateSpanRouteName(isolationScope: Scope, context: Context): void {

const rootSpan = getRootSpan(activeSpan);
updateSpanName(rootSpan, routeName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

isolationScope.setTransactionName(routeName);
Expand Down
13 changes: 13 additions & 0 deletions packages/hono/test/shared/middlewareHandlers.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { requestHandler, responseHandler } from '../../src/shared/middlewareHandlers';

Expand DownExpand Up@@ -245,6 +246,18 @@ describe('responseHandler', () => {

expect(mockSetTransactionName).toHaveBeenCalledWith('GET /test');
});

it('sets http.route on the root span', () => {
getActiveSpanMock.mockReturnValue(mockRootSpan);

// oxlint-disable-next-line typescript/no-explicit-any
requestHandler(createMockContext(200) as any);

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/test',
});
});
});
});

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import type { NextApiRequest } from 'next';
import type { AugmentedNextApiResponse, NextApiHandler } from '../types';
import { flushSafelyWithTimeout, waitUntil } from '../utils/responseEnd';
import { dropNextjsRootContext, escapeNextjsTracing } from '../utils/tracingUtils';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

export type AugmentedNextApiRequest = NextApiRequest & {
__withSentry_applied__?: boolean;
Expand DownExpand Up@@ -94,6 +94,7 @@ export function wrapApiHandlerWithSentry(apiHandler: NextApiHandler, parameteriz
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: urlObject && !isURLObjectRelative(urlObject) ? urlObject.href : undefined,
[URL_PATH]: urlObject?.pathname,
[HTTP_ROUTE]: parameterizedRoute,
},
},
async span => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { Event } from '@sentry/core';
import { getClient } from '@sentry/core';
import { URL_PATH } from '@sentry/conventions/attributes';
import { getSanitizedRequestUrl } from './urls';

/**
Expand All@@ -20,7 +21,7 @@ export function setUrlProcessingMetadata(event: Event): void {

// Get the route from trace data
const componentRoute = traceData['next.route'] || traceData['http.route'];
const httpTarget = traceData['http.target'] as string | undefined;
const httpTarget = (traceData['http.target'] || traceData[URL_PATH]) as string | undefined;

if (!componentRoute) {
return;
Expand Down
8 changes: 6 additions & 2 deletions packages/nextjs/src/common/wrapRouteHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavi
import type { RouteHandlerContext } from './types';
import { flushSafelyWithTimeout, waitUntil } from './utils/responseEnd';
import { commonObjectToIsolationScope } from './utils/tracingUtils';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js App Router Route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -47,8 +48,11 @@ export function wrapRouteHandlerWithSentry<F extends (...args: any[]) => any>(
edgeRuntimeIsolationScopeOverride = isolationScope;

rootSpan.updateName(`${method} ${parameterizedRoute}`);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'http.server');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[HTTP_ROUTE]: parameterizedRoute,
});
}

return withIsolationScope(
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/src/edge/wrapApiHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import {
import { addHeadersAsAttributes } from '../common/utils/addHeadersAsAttributes';
import { flushSafelyWithTimeout, waitUntil } from '../common/utils/responseEnd';
import type { EdgeRouteHandler } from './types';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js edge route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -75,6 +75,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: rootSpanAttributes[URL_FULL] ?? urlAttributes[URL_FULL],
[URL_PATH]: rootSpanAttributes[URL_PATH] ?? urlAttributes[URL_PATH],
[HTTP_ROUTE]: parameterizedRoute,
...headerAttributes,
});
setCapturedScopesOnSpan(rootSpan, currentScope, isolationScope);
Expand All@@ -92,6 +93,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs.wrap_api_handler',
[HTTP_ROUTE]: parameterizedRoute,
...urlAttributes,
...headerAttributes,
},
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/src/server/enhanceHandleRequestRootSpan.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const cleanRoute = route.replace(/\/route$/, '');
span.setName(`${method} ${cleanRoute}`);
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';
attributes[HTTP_ROUTE] = cleanRoute;
// Preserve next.route in case it did not get hoisted
attributes[ATTR_NEXT_ROUTE] = cleanRoute;
}
Expand All@@ -55,6 +56,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const routeBackfill = attributes[TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL];
if (typeof routeBackfill === 'string' && span.getName() !== 'GET /_app') {
span.setName(`${typeof method === 'string' ? method : 'GET'} ${routeBackfill}`);
attributes[HTTP_ROUTE] = attributes[HTTP_ROUTE] ?? routeBackfill;
}

const middlewareMatch =
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import * as SentryCore from '@sentry/core';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
Expand DownExpand Up@@ -55,6 +55,7 @@ describe('withSentry', () => {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: 'https://dogs.are.great/api/dogs?good=true',
[URL_PATH]: '/api/dogs',
[HTTP_ROUTE]: '/my-parameterized-route',
},
},
expect.any(Function),
Expand Down
53 changes: 51 additions & 2 deletions packages/nextjs/test/edge/withSentryAPI.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
import { afterAll, afterEach, describe, it, vi } from 'vitest';
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { wrapApiHandlerWithSentry } from '../../src/edge';

const origRequest = global.Request;
Expand DownExpand Up@@ -30,7 +33,7 @@ afterAll(() => {
});

afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
});

describe('wrapApiHandlerWithSentry', () => {
Expand All@@ -41,4 +44,50 @@ describe('wrapApiHandlerWithSentry', () => {

await wrappedFunction();
});

it('adds normalized request URL and route attributes to the active root span', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({ data: {} } as any);
const origFunction = vi.fn(() => new Response());
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(origFunction, parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456?good=true'));

expect(rootSpan.updateName).toHaveBeenCalledWith(`POST ${parameterizedRoute}`);
expect(rootSpan.setAttributes).toHaveBeenCalledWith({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: 'https://dogs.are.great/user/123/post/456?good=true',
[URL_PATH]: '/user/123/post/456',
[HTTP_ROUTE]: parameterizedRoute,
});
});

it('replaces a concrete root span route with the parameterized route', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({
data: { [HTTP_ROUTE]: '/user/123/post/456' },
} as any);
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(() => new Response(), parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456'));

expect(rootSpan.setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
[HTTP_ROUTE]: parameterizedRoute,
}),
);
});
});
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { describe, expect, it } from 'vitest';
import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_NAME, ATTR_NEXT_SPAN_TYPE } from '../../src/common/nextSpanAttributes';
Expand DownExpand Up@@ -48,6 +49,7 @@ describe('enhanceHandleRequestRootSpan', () => {
expect(getName()).toBe('GET /api/users/[id]');
expect(span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]).toBe('route');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/users/[id]');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/users/[id]');
});

it('strips trailing /route from app router route handler routes', () => {
Expand All@@ -64,6 +66,7 @@ describe('enhanceHandleRequestRootSpan', () => {

expect(getName()).toBe('POST /api/widgets');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/widgets');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/widgets');
});

it('strips URL query and fragment from the segment name', () => {
Expand DownExpand Up@@ -105,6 +108,7 @@ describe('enhanceHandleRequestRootSpan', () => {
enhanceHandleRequestRootSpan(span);

expect(getName()).toBe('GET /posts/[slug]');
expect(span.attributes[HTTP_ROUTE]).toBe('/posts/[slug]');
});

it('does not apply the backfill for the special GET /_app transaction', () => {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ test('Sends parameterized transaction name to Sentry', async ({ page }) => {

expect(transaction).toBeDefined();
expect(transaction.transaction).toBe('GET user/:id');
expect(transaction.contexts?.trace?.data?.['http.route']).toBe('user/:id');
});

test('Sends form data with action span', async ({ page }) => {
Expand DownExpand Up@@ -271,6 +272,7 @@ test('Sends two linked transactions (server & client) to Sentry', async ({ page
const pageLoadParentSpanId = pageloadTransaction.contexts?.trace?.parent_span_id;

expect(httpServerTransaction.transaction).toBe('GET http://localhost:3030/');
expect(httpServerTransaction.contexts?.trace?.data?.['http.route']).toBeUndefined();
expect(pageloadTransaction.transaction).toBe('/');

expect(httpServerTraceId).toBeDefined();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,7 +42,7 @@ test('should trace orpc server component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/list',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand DownExpand Up@@ -99,7 +99,7 @@ test('should trace orpc client component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/find',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand Down
16 changes: 11 additions & 5 deletions packages/elysia/src/withElysia.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import {
captureException,
Expand DownExpand Up@@ -60,18 +60,24 @@ const instrumentedApps = new WeakSet<Elysia>();
function updateRouteTransactionName(request: Request, method: string, route: string): void {
const transactionName = `${method} ${route}`;

function applyRouteToSpan(span: Span): void {
updateSpanName(span, transactionName);
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

// Try the stored root span first (reliable across async contexts),
// then fall back to getActiveSpan() for cases where async context is preserved.
const rootSpan = rootSpanForRequest.get(request);
if (rootSpan) {
updateSpanName(rootSpan, transactionName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(rootSpan);
} else {
const activeSpan = getActiveSpan();
if (activeSpan) {
const root = getRootSpan(activeSpan);
updateSpanName(root, transactionName);
root.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(root);
}
}

Expand Down
26 changes: 26 additions & 0 deletions packages/elysia/test/withElysia.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import type { ErrorContext } from 'elysia';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

Expand DownExpand Up@@ -32,6 +33,12 @@ const mockGetIsolationScope = vi.fn(() => ({
const mockGetClient = vi.fn(() => ({
on: vi.fn(),
}));
const mockRootSpan = {
setAttributes: vi.fn(),
updateName: vi.fn(),
};
const mockGetActiveSpan = vi.fn();
const mockGetRootSpan = vi.fn(() => mockRootSpan);
const mockGetTraceData = vi.fn(() => ({
'sentry-trace': 'abc123-def456-1',
baggage: 'sentry-environment=test,sentry-trace_id=abc123',
Expand All@@ -43,8 +50,10 @@ vi.mock('@sentry/core', async importActual => {
return {
...actual,
captureException: (...args: unknown[]) => mockCaptureException(...args),
getActiveSpan: () => mockGetActiveSpan(),
getIsolationScope: () => mockGetIsolationScope(),
getClient: () => mockGetClient(),
getRootSpan: () => mockGetRootSpan(),
getTraceData: () => mockGetTraceData(),
};
});
Expand DownExpand Up@@ -88,6 +97,23 @@ describe('withElysia', () => {
expect(headers['baggage']).toBe('sentry-environment=test,sentry-trace_id=abc123');
});

it('sets the matched route on the root span', () => {
mockGetActiveSpan.mockReturnValueOnce(mockRootSpan);
// @ts-expect-error - mock app
withElysia(mockApp);

onAfterHandleHandler({
route: '/users/:id',
request: new Request('https://example.com/users/42', { method: 'GET' }),
set: { headers: {} },
});

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/users/:id',
});
});

it('does not set headers when trace data is empty', () => {
mockGetTraceData.mockReturnValueOnce({});
// @ts-expect-error - mock app
Expand Down
3 changes: 2 additions & 1 deletion packages/hono/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -92,7 +92,8 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"@sentry/conventions": "^0.16.0"
},
"peerDependencies": {
"@cloudflare/workers-types": "^4.x",
Expand Down
9 changes: 7 additions & 2 deletions packages/hono/src/shared/middlewareHandlers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import { defaultShouldHandleError } from './defaultShouldHandleError';
import { resolveRouteName } from './resolveRouteName';
import { type SentryHonoMiddlewareOptions } from '../shared/types';
import { type GetConnInfo } from 'hono/conninfo';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Request handler for Hono framework
Expand DownExpand Up@@ -99,7 +100,8 @@ export function responseHandler(
}

function updateSpanRouteName(isolationScope: Scope, context: Context): void {
const routeName = `${context.req.method} ${resolveRouteName(context)}`;
const route = resolveRouteName(context);
const routeName = `${context.req.method} ${route}`;
const activeSpan = getActiveSpan();

if (activeSpan) {
Expand All@@ -108,7 +110,10 @@ function updateSpanRouteName(isolationScope: Scope, context: Context): void {

const rootSpan = getRootSpan(activeSpan);
updateSpanName(rootSpan, routeName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

isolationScope.setTransactionName(routeName);
Expand Down
13 changes: 13 additions & 0 deletions packages/hono/test/shared/middlewareHandlers.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { requestHandler, responseHandler } from '../../src/shared/middlewareHandlers';

Expand DownExpand Up@@ -245,6 +246,18 @@ describe('responseHandler', () => {

expect(mockSetTransactionName).toHaveBeenCalledWith('GET /test');
});

it('sets http.route on the root span', () => {
getActiveSpanMock.mockReturnValue(mockRootSpan);

// oxlint-disable-next-line typescript/no-explicit-any
requestHandler(createMockContext(200) as any);

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/test',
});
});
});
});

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import type { NextApiRequest } from 'next';
import type { AugmentedNextApiResponse, NextApiHandler } from '../types';
import { flushSafelyWithTimeout, waitUntil } from '../utils/responseEnd';
import { dropNextjsRootContext, escapeNextjsTracing } from '../utils/tracingUtils';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

export type AugmentedNextApiRequest = NextApiRequest & {
__withSentry_applied__?: boolean;
Expand DownExpand Up@@ -94,6 +94,7 @@ export function wrapApiHandlerWithSentry(apiHandler: NextApiHandler, parameteriz
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: urlObject && !isURLObjectRelative(urlObject) ? urlObject.href : undefined,
[URL_PATH]: urlObject?.pathname,
[HTTP_ROUTE]: parameterizedRoute,
},
},
async span => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { Event } from '@sentry/core';
import { getClient } from '@sentry/core';
import { URL_PATH } from '@sentry/conventions/attributes';
import { getSanitizedRequestUrl } from './urls';

/**
Expand All@@ -20,7 +21,7 @@ export function setUrlProcessingMetadata(event: Event): void {

// Get the route from trace data
const componentRoute = traceData['next.route'] || traceData['http.route'];
const httpTarget = traceData['http.target'] as string | undefined;
const httpTarget = (traceData['http.target'] || traceData[URL_PATH]) as string | undefined;

if (!componentRoute) {
return;
Expand Down
8 changes: 6 additions & 2 deletions packages/nextjs/src/common/wrapRouteHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavi
import type { RouteHandlerContext } from './types';
import { flushSafelyWithTimeout, waitUntil } from './utils/responseEnd';
import { commonObjectToIsolationScope } from './utils/tracingUtils';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js App Router Route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -47,8 +48,11 @@ export function wrapRouteHandlerWithSentry<F extends (...args: any[]) => any>(
edgeRuntimeIsolationScopeOverride = isolationScope;

rootSpan.updateName(`${method} ${parameterizedRoute}`);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'http.server');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[HTTP_ROUTE]: parameterizedRoute,
});
}

return withIsolationScope(
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/src/edge/wrapApiHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import {
import { addHeadersAsAttributes } from '../common/utils/addHeadersAsAttributes';
import { flushSafelyWithTimeout, waitUntil } from '../common/utils/responseEnd';
import type { EdgeRouteHandler } from './types';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js edge route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -75,6 +75,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: rootSpanAttributes[URL_FULL] ?? urlAttributes[URL_FULL],
[URL_PATH]: rootSpanAttributes[URL_PATH] ?? urlAttributes[URL_PATH],
[HTTP_ROUTE]: parameterizedRoute,
...headerAttributes,
});
setCapturedScopesOnSpan(rootSpan, currentScope, isolationScope);
Expand All@@ -92,6 +93,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs.wrap_api_handler',
[HTTP_ROUTE]: parameterizedRoute,
...urlAttributes,
...headerAttributes,
},
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/src/server/enhanceHandleRequestRootSpan.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const cleanRoute = route.replace(/\/route$/, '');
span.setName(`${method} ${cleanRoute}`);
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';
attributes[HTTP_ROUTE] = cleanRoute;
// Preserve next.route in case it did not get hoisted
attributes[ATTR_NEXT_ROUTE] = cleanRoute;
}
Expand All@@ -55,6 +56,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const routeBackfill = attributes[TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL];
if (typeof routeBackfill === 'string' && span.getName() !== 'GET /_app') {
span.setName(`${typeof method === 'string' ? method : 'GET'} ${routeBackfill}`);
attributes[HTTP_ROUTE] = attributes[HTTP_ROUTE] ?? routeBackfill;
}

const middlewareMatch =
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import * as SentryCore from '@sentry/core';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
Expand DownExpand Up@@ -55,6 +55,7 @@ describe('withSentry', () => {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: 'https://dogs.are.great/api/dogs?good=true',
[URL_PATH]: '/api/dogs',
[HTTP_ROUTE]: '/my-parameterized-route',
},
},
expect.any(Function),
Expand Down
53 changes: 51 additions & 2 deletions packages/nextjs/test/edge/withSentryAPI.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
import { afterAll, afterEach, describe, it, vi } from 'vitest';
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { wrapApiHandlerWithSentry } from '../../src/edge';

const origRequest = global.Request;
Expand DownExpand Up@@ -30,7 +33,7 @@ afterAll(() => {
});

afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
});

describe('wrapApiHandlerWithSentry', () => {
Expand All@@ -41,4 +44,50 @@ describe('wrapApiHandlerWithSentry', () => {

await wrappedFunction();
});

it('adds normalized request URL and route attributes to the active root span', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({ data: {} } as any);
const origFunction = vi.fn(() => new Response());
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(origFunction, parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456?good=true'));

expect(rootSpan.updateName).toHaveBeenCalledWith(`POST ${parameterizedRoute}`);
expect(rootSpan.setAttributes).toHaveBeenCalledWith({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: 'https://dogs.are.great/user/123/post/456?good=true',
[URL_PATH]: '/user/123/post/456',
[HTTP_ROUTE]: parameterizedRoute,
});
});

it('replaces a concrete root span route with the parameterized route', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({
data: { [HTTP_ROUTE]: '/user/123/post/456' },
} as any);
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(() => new Response(), parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456'));

expect(rootSpan.setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
[HTTP_ROUTE]: parameterizedRoute,
}),
);
});
});
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { describe, expect, it } from 'vitest';
import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_NAME, ATTR_NEXT_SPAN_TYPE } from '../../src/common/nextSpanAttributes';
Expand DownExpand Up@@ -48,6 +49,7 @@ describe('enhanceHandleRequestRootSpan', () => {
expect(getName()).toBe('GET /api/users/[id]');
expect(span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]).toBe('route');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/users/[id]');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/users/[id]');
});

it('strips trailing /route from app router route handler routes', () => {
Expand All@@ -64,6 +66,7 @@ describe('enhanceHandleRequestRootSpan', () => {

expect(getName()).toBe('POST /api/widgets');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/widgets');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/widgets');
});

it('strips URL query and fragment from the segment name', () => {
Expand DownExpand Up@@ -105,6 +108,7 @@ describe('enhanceHandleRequestRootSpan', () => {
enhanceHandleRequestRootSpan(span);

expect(getName()).toBe('GET /posts/[slug]');
expect(span.attributes[HTTP_ROUTE]).toBe('/posts/[slug]');
});

it('does not apply the backfill for the special GET /_app transaction', () => {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ test('Sends parameterized transaction name to Sentry', async ({ page }) => {

expect(transaction).toBeDefined();
expect(transaction.transaction).toBe('GET user/:id');
expect(transaction.contexts?.trace?.data?.['http.route']).toBe('user/:id');
});

test('Sends form data with action span', async ({ page }) => {
Expand DownExpand Up@@ -271,6 +272,7 @@ test('Sends two linked transactions (server & client) to Sentry', async ({ page
const pageLoadParentSpanId = pageloadTransaction.contexts?.trace?.parent_span_id;

expect(httpServerTransaction.transaction).toBe('GET http://localhost:3030/');
expect(httpServerTransaction.contexts?.trace?.data?.['http.route']).toBeUndefined();
expect(pageloadTransaction.transaction).toBe('/');

expect(httpServerTraceId).toBeDefined();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,7 +42,7 @@ test('should trace orpc server component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/list',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand DownExpand Up@@ -99,7 +99,7 @@ test('should trace orpc client component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/find',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand Down
16 changes: 11 additions & 5 deletions packages/elysia/src/withElysia.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import {
captureException,
Expand DownExpand Up@@ -60,18 +60,24 @@ const instrumentedApps = new WeakSet<Elysia>();
function updateRouteTransactionName(request: Request, method: string, route: string): void {
const transactionName = `${method} ${route}`;

function applyRouteToSpan(span: Span): void {
updateSpanName(span, transactionName);
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

// Try the stored root span first (reliable across async contexts),
// then fall back to getActiveSpan() for cases where async context is preserved.
const rootSpan = rootSpanForRequest.get(request);
if (rootSpan) {
updateSpanName(rootSpan, transactionName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(rootSpan);
} else {
const activeSpan = getActiveSpan();
if (activeSpan) {
const root = getRootSpan(activeSpan);
updateSpanName(root, transactionName);
root.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(root);
}
}

Expand Down
26 changes: 26 additions & 0 deletions packages/elysia/test/withElysia.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import type { ErrorContext } from 'elysia';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

Expand DownExpand Up@@ -32,6 +33,12 @@ const mockGetIsolationScope = vi.fn(() => ({
const mockGetClient = vi.fn(() => ({
on: vi.fn(),
}));
const mockRootSpan = {
setAttributes: vi.fn(),
updateName: vi.fn(),
};
const mockGetActiveSpan = vi.fn();
const mockGetRootSpan = vi.fn(() => mockRootSpan);
const mockGetTraceData = vi.fn(() => ({
'sentry-trace': 'abc123-def456-1',
baggage: 'sentry-environment=test,sentry-trace_id=abc123',
Expand All@@ -43,8 +50,10 @@ vi.mock('@sentry/core', async importActual => {
return {
...actual,
captureException: (...args: unknown[]) => mockCaptureException(...args),
getActiveSpan: () => mockGetActiveSpan(),
getIsolationScope: () => mockGetIsolationScope(),
getClient: () => mockGetClient(),
getRootSpan: () => mockGetRootSpan(),
getTraceData: () => mockGetTraceData(),
};
});
Expand DownExpand Up@@ -88,6 +97,23 @@ describe('withElysia', () => {
expect(headers['baggage']).toBe('sentry-environment=test,sentry-trace_id=abc123');
});

it('sets the matched route on the root span', () => {
mockGetActiveSpan.mockReturnValueOnce(mockRootSpan);
// @ts-expect-error - mock app
withElysia(mockApp);

onAfterHandleHandler({
route: '/users/:id',
request: new Request('https://example.com/users/42', { method: 'GET' }),
set: { headers: {} },
});

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/users/:id',
});
});

it('does not set headers when trace data is empty', () => {
mockGetTraceData.mockReturnValueOnce({});
// @ts-expect-error - mock app
Expand Down
3 changes: 2 additions & 1 deletion packages/hono/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -92,7 +92,8 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"@sentry/conventions": "^0.16.0"
},
"peerDependencies": {
"@cloudflare/workers-types": "^4.x",
Expand Down
9 changes: 7 additions & 2 deletions packages/hono/src/shared/middlewareHandlers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import { defaultShouldHandleError } from './defaultShouldHandleError';
import { resolveRouteName } from './resolveRouteName';
import { type SentryHonoMiddlewareOptions } from '../shared/types';
import { type GetConnInfo } from 'hono/conninfo';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Request handler for Hono framework
Expand DownExpand Up@@ -99,7 +100,8 @@ export function responseHandler(
}

function updateSpanRouteName(isolationScope: Scope, context: Context): void {
const routeName = `${context.req.method} ${resolveRouteName(context)}`;
const route = resolveRouteName(context);
const routeName = `${context.req.method} ${route}`;
const activeSpan = getActiveSpan();

if (activeSpan) {
Expand All@@ -108,7 +110,10 @@ function updateSpanRouteName(isolationScope: Scope, context: Context): void {

const rootSpan = getRootSpan(activeSpan);
updateSpanName(rootSpan, routeName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

isolationScope.setTransactionName(routeName);
Expand Down
13 changes: 13 additions & 0 deletions packages/hono/test/shared/middlewareHandlers.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { requestHandler, responseHandler } from '../../src/shared/middlewareHandlers';

Expand DownExpand Up@@ -245,6 +246,18 @@ describe('responseHandler', () => {

expect(mockSetTransactionName).toHaveBeenCalledWith('GET /test');
});

it('sets http.route on the root span', () => {
getActiveSpanMock.mockReturnValue(mockRootSpan);

// oxlint-disable-next-line typescript/no-explicit-any
requestHandler(createMockContext(200) as any);

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/test',
});
});
});
});

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import type { NextApiRequest } from 'next';
import type { AugmentedNextApiResponse, NextApiHandler } from '../types';
import { flushSafelyWithTimeout, waitUntil } from '../utils/responseEnd';
import { dropNextjsRootContext, escapeNextjsTracing } from '../utils/tracingUtils';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

export type AugmentedNextApiRequest = NextApiRequest & {
__withSentry_applied__?: boolean;
Expand DownExpand Up@@ -94,6 +94,7 @@ export function wrapApiHandlerWithSentry(apiHandler: NextApiHandler, parameteriz
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: urlObject && !isURLObjectRelative(urlObject) ? urlObject.href : undefined,
[URL_PATH]: urlObject?.pathname,
[HTTP_ROUTE]: parameterizedRoute,
},
},
async span => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { Event } from '@sentry/core';
import { getClient } from '@sentry/core';
import { URL_PATH } from '@sentry/conventions/attributes';
import { getSanitizedRequestUrl } from './urls';

/**
Expand All@@ -20,7 +21,7 @@ export function setUrlProcessingMetadata(event: Event): void {

// Get the route from trace data
const componentRoute = traceData['next.route'] || traceData['http.route'];
const httpTarget = traceData['http.target'] as string | undefined;
const httpTarget = (traceData['http.target'] || traceData[URL_PATH]) as string | undefined;

if (!componentRoute) {
return;
Expand Down
8 changes: 6 additions & 2 deletions packages/nextjs/src/common/wrapRouteHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavi
import type { RouteHandlerContext } from './types';
import { flushSafelyWithTimeout, waitUntil } from './utils/responseEnd';
import { commonObjectToIsolationScope } from './utils/tracingUtils';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js App Router Route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -47,8 +48,11 @@ export function wrapRouteHandlerWithSentry<F extends (...args: any[]) => any>(
edgeRuntimeIsolationScopeOverride = isolationScope;

rootSpan.updateName(`${method} ${parameterizedRoute}`);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'http.server');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[HTTP_ROUTE]: parameterizedRoute,
});
}

return withIsolationScope(
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/src/edge/wrapApiHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import {
import { addHeadersAsAttributes } from '../common/utils/addHeadersAsAttributes';
import { flushSafelyWithTimeout, waitUntil } from '../common/utils/responseEnd';
import type { EdgeRouteHandler } from './types';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js edge route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -75,6 +75,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: rootSpanAttributes[URL_FULL] ?? urlAttributes[URL_FULL],
[URL_PATH]: rootSpanAttributes[URL_PATH] ?? urlAttributes[URL_PATH],
[HTTP_ROUTE]: parameterizedRoute,
...headerAttributes,
});
setCapturedScopesOnSpan(rootSpan, currentScope, isolationScope);
Expand All@@ -92,6 +93,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs.wrap_api_handler',
[HTTP_ROUTE]: parameterizedRoute,
...urlAttributes,
...headerAttributes,
},
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/src/server/enhanceHandleRequestRootSpan.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const cleanRoute = route.replace(/\/route$/, '');
span.setName(`${method} ${cleanRoute}`);
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';
attributes[HTTP_ROUTE] = cleanRoute;
// Preserve next.route in case it did not get hoisted
attributes[ATTR_NEXT_ROUTE] = cleanRoute;
}
Expand All@@ -55,6 +56,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const routeBackfill = attributes[TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL];
if (typeof routeBackfill === 'string' && span.getName() !== 'GET /_app') {
span.setName(`${typeof method === 'string' ? method : 'GET'} ${routeBackfill}`);
attributes[HTTP_ROUTE] = attributes[HTTP_ROUTE] ?? routeBackfill;
}

const middlewareMatch =
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import * as SentryCore from '@sentry/core';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
Expand DownExpand Up@@ -55,6 +55,7 @@ describe('withSentry', () => {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: 'https://dogs.are.great/api/dogs?good=true',
[URL_PATH]: '/api/dogs',
[HTTP_ROUTE]: '/my-parameterized-route',
},
},
expect.any(Function),
Expand Down
53 changes: 51 additions & 2 deletions packages/nextjs/test/edge/withSentryAPI.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
import { afterAll, afterEach, describe, it, vi } from 'vitest';
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { wrapApiHandlerWithSentry } from '../../src/edge';

const origRequest = global.Request;
Expand DownExpand Up@@ -30,7 +33,7 @@ afterAll(() => {
});

afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
});

describe('wrapApiHandlerWithSentry', () => {
Expand All@@ -41,4 +44,50 @@ describe('wrapApiHandlerWithSentry', () => {

await wrappedFunction();
});

it('adds normalized request URL and route attributes to the active root span', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({ data: {} } as any);
const origFunction = vi.fn(() => new Response());
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(origFunction, parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456?good=true'));

expect(rootSpan.updateName).toHaveBeenCalledWith(`POST ${parameterizedRoute}`);
expect(rootSpan.setAttributes).toHaveBeenCalledWith({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: 'https://dogs.are.great/user/123/post/456?good=true',
[URL_PATH]: '/user/123/post/456',
[HTTP_ROUTE]: parameterizedRoute,
});
});

it('replaces a concrete root span route with the parameterized route', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({
data: { [HTTP_ROUTE]: '/user/123/post/456' },
} as any);
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(() => new Response(), parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456'));

expect(rootSpan.setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
[HTTP_ROUTE]: parameterizedRoute,
}),
);
});
});
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { describe, expect, it } from 'vitest';
import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_NAME, ATTR_NEXT_SPAN_TYPE } from '../../src/common/nextSpanAttributes';
Expand DownExpand Up@@ -48,6 +49,7 @@ describe('enhanceHandleRequestRootSpan', () => {
expect(getName()).toBe('GET /api/users/[id]');
expect(span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]).toBe('route');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/users/[id]');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/users/[id]');
});

it('strips trailing /route from app router route handler routes', () => {
Expand All@@ -64,6 +66,7 @@ describe('enhanceHandleRequestRootSpan', () => {

expect(getName()).toBe('POST /api/widgets');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/widgets');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/widgets');
});

it('strips URL query and fragment from the segment name', () => {
Expand DownExpand Up@@ -105,6 +108,7 @@ describe('enhanceHandleRequestRootSpan', () => {
enhanceHandleRequestRootSpan(span);

expect(getName()).toBe('GET /posts/[slug]');
expect(span.attributes[HTTP_ROUTE]).toBe('/posts/[slug]');
});

it('does not apply the backfill for the special GET /_app transaction', () => {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,7 @@ test('Sends parameterized transaction name to Sentry', async ({ page }) => {

expect(transaction).toBeDefined();
expect(transaction.transaction).toBe('GET user/:id');
expect(transaction.contexts?.trace?.data?.['http.route']).toBe('user/:id');
});

test('Sends form data with action span', async ({ page }) => {
Expand DownExpand Up@@ -271,6 +272,7 @@ test('Sends two linked transactions (server & client) to Sentry', async ({ page
const pageLoadParentSpanId = pageloadTransaction.contexts?.trace?.parent_span_id;

expect(httpServerTransaction.transaction).toBe('GET http://localhost:3030/');
expect(httpServerTransaction.contexts?.trace?.data?.['http.route']).toBeUndefined();
expect(pageloadTransaction.transaction).toBe('/');

expect(httpServerTraceId).toBeDefined();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,7 +42,7 @@ test('should trace orpc server component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/list',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand DownExpand Up@@ -99,7 +99,7 @@ test('should trace orpc client component', async ({ page }) => {
'http.method': 'POST',
'http.target': '/rpc/planet/find',
'next.rsc': false,
'http.route': '/rpc/[[...rest]]/route',
'http.route': '/rpc/[[...rest]]',
'next.route': '/rpc/[[...rest]]',
'http.status_code': 200,
},
Expand Down
16 changes: 11 additions & 5 deletions packages/elysia/src/withElysia.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import {
captureException,
Expand DownExpand Up@@ -60,18 +60,24 @@ const instrumentedApps = new WeakSet<Elysia>();
function updateRouteTransactionName(request: Request, method: string, route: string): void {
const transactionName = `${method} ${route}`;

function applyRouteToSpan(span: Span): void {
updateSpanName(span, transactionName);
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

// Try the stored root span first (reliable across async contexts),
// then fall back to getActiveSpan() for cases where async context is preserved.
const rootSpan = rootSpanForRequest.get(request);
if (rootSpan) {
updateSpanName(rootSpan, transactionName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(rootSpan);
} else {
const activeSpan = getActiveSpan();
if (activeSpan) {
const root = getRootSpan(activeSpan);
updateSpanName(root, transactionName);
root.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
applyRouteToSpan(root);
}
}

Expand Down
26 changes: 26 additions & 0 deletions packages/elysia/test/withElysia.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import type { ErrorContext } from 'elysia';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

Expand DownExpand Up@@ -32,6 +33,12 @@ const mockGetIsolationScope = vi.fn(() => ({
const mockGetClient = vi.fn(() => ({
on: vi.fn(),
}));
const mockRootSpan = {
setAttributes: vi.fn(),
updateName: vi.fn(),
};
const mockGetActiveSpan = vi.fn();
const mockGetRootSpan = vi.fn(() => mockRootSpan);
const mockGetTraceData = vi.fn(() => ({
'sentry-trace': 'abc123-def456-1',
baggage: 'sentry-environment=test,sentry-trace_id=abc123',
Expand All@@ -43,8 +50,10 @@ vi.mock('@sentry/core', async importActual => {
return {
...actual,
captureException: (...args: unknown[]) => mockCaptureException(...args),
getActiveSpan: () => mockGetActiveSpan(),
getIsolationScope: () => mockGetIsolationScope(),
getClient: () => mockGetClient(),
getRootSpan: () => mockGetRootSpan(),
getTraceData: () => mockGetTraceData(),
};
});
Expand DownExpand Up@@ -88,6 +97,23 @@ describe('withElysia', () => {
expect(headers['baggage']).toBe('sentry-environment=test,sentry-trace_id=abc123');
});

it('sets the matched route on the root span', () => {
mockGetActiveSpan.mockReturnValueOnce(mockRootSpan);
// @ts-expect-error - mock app
withElysia(mockApp);

onAfterHandleHandler({
route: '/users/:id',
request: new Request('https://example.com/users/42', { method: 'GET' }),
set: { headers: {} },
});

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/users/:id',
});
});

it('does not set headers when trace data is empty', () => {
mockGetTraceData.mockReturnValueOnce({});
// @ts-expect-error - mock app
Expand Down
3 changes: 2 additions & 1 deletion packages/hono/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -92,7 +92,8 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"@sentry/conventions": "^0.16.0"
},
"peerDependencies": {
"@cloudflare/workers-types": "^4.x",
Expand Down
9 changes: 7 additions & 2 deletions packages/hono/src/shared/middlewareHandlers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import { defaultShouldHandleError } from './defaultShouldHandleError';
import { resolveRouteName } from './resolveRouteName';
import { type SentryHonoMiddlewareOptions } from '../shared/types';
import { type GetConnInfo } from 'hono/conninfo';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Request handler for Hono framework
Expand DownExpand Up@@ -99,7 +100,8 @@ export function responseHandler(
}

function updateSpanRouteName(isolationScope: Scope, context: Context): void {
const routeName = `${context.req.method} ${resolveRouteName(context)}`;
const route = resolveRouteName(context);
const routeName = `${context.req.method} ${route}`;
const activeSpan = getActiveSpan();

if (activeSpan) {
Expand All@@ -108,7 +110,10 @@ function updateSpanRouteName(isolationScope: Scope, context: Context): void {

const rootSpan = getRootSpan(activeSpan);
updateSpanName(rootSpan, routeName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[HTTP_ROUTE]: route,
});
}

isolationScope.setTransactionName(routeName);
Expand Down
13 changes: 13 additions & 0 deletions packages/hono/test/shared/middlewareHandlers.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { requestHandler, responseHandler } from '../../src/shared/middlewareHandlers';

Expand DownExpand Up@@ -245,6 +246,18 @@ describe('responseHandler', () => {

expect(mockSetTransactionName).toHaveBeenCalledWith('GET /test');
});

it('sets http.route on the root span', () => {
getActiveSpanMock.mockReturnValue(mockRootSpan);

// oxlint-disable-next-line typescript/no-explicit-any
requestHandler(createMockContext(200) as any);

expect(mockRootSpan.setAttributes).toHaveBeenCalledWith({
'sentry.source': 'route',
[HTTP_ROUTE]: '/test',
});
});
});
});

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import type { NextApiRequest } from 'next';
import type { AugmentedNextApiResponse, NextApiHandler } from '../types';
import { flushSafelyWithTimeout, waitUntil } from '../utils/responseEnd';
import { dropNextjsRootContext, escapeNextjsTracing } from '../utils/tracingUtils';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

export type AugmentedNextApiRequest = NextApiRequest & {
__withSentry_applied__?: boolean;
Expand DownExpand Up@@ -94,6 +94,7 @@ export function wrapApiHandlerWithSentry(apiHandler: NextApiHandler, parameteriz
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: urlObject && !isURLObjectRelative(urlObject) ? urlObject.href : undefined,
[URL_PATH]: urlObject?.pathname,
[HTTP_ROUTE]: parameterizedRoute,
},
},
async span => {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { Event } from '@sentry/core';
import { getClient } from '@sentry/core';
import { URL_PATH } from '@sentry/conventions/attributes';
import { getSanitizedRequestUrl } from './urls';

/**
Expand All@@ -20,7 +21,7 @@ export function setUrlProcessingMetadata(event: Event): void {

// Get the route from trace data
const componentRoute = traceData['next.route'] || traceData['http.route'];
const httpTarget = traceData['http.target'] as string | undefined;
const httpTarget = (traceData['http.target'] || traceData[URL_PATH]) as string | undefined;

if (!componentRoute) {
return;
Expand Down
8 changes: 6 additions & 2 deletions packages/nextjs/src/common/wrapRouteHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavi
import type { RouteHandlerContext } from './types';
import { flushSafelyWithTimeout, waitUntil } from './utils/responseEnd';
import { commonObjectToIsolationScope } from './utils/tracingUtils';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js App Router Route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -47,8 +48,11 @@ export function wrapRouteHandlerWithSentry<F extends (...args: any[]) => any>(
edgeRuntimeIsolationScopeOverride = isolationScope;

rootSpan.updateName(`${method} ${parameterizedRoute}`);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'http.server');
rootSpan.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[HTTP_ROUTE]: parameterizedRoute,
});
}

return withIsolationScope(
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/src/edge/wrapApiHandlerWithSentry.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@ import {
import { addHeadersAsAttributes } from '../common/utils/addHeadersAsAttributes';
import { flushSafelyWithTimeout, waitUntil } from '../common/utils/responseEnd';
import type { EdgeRouteHandler } from './types';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';

/**
* Wraps a Next.js edge route handler with Sentry error and performance instrumentation.
Expand DownExpand Up@@ -75,6 +75,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: rootSpanAttributes[URL_FULL] ?? urlAttributes[URL_FULL],
[URL_PATH]: rootSpanAttributes[URL_PATH] ?? urlAttributes[URL_PATH],
[HTTP_ROUTE]: parameterizedRoute,
...headerAttributes,
});
setCapturedScopesOnSpan(rootSpan, currentScope, isolationScope);
Expand All@@ -92,6 +93,7 @@ export function wrapApiHandlerWithSentry<H extends EdgeRouteHandler>(
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.nextjs.wrap_api_handler',
[HTTP_ROUTE]: parameterizedRoute,
...urlAttributes,
...headerAttributes,
},
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/src/server/enhanceHandleRequestRootSpan.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const cleanRoute = route.replace(/\/route$/, '');
span.setName(`${method} ${cleanRoute}`);
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';
attributes[HTTP_ROUTE] = cleanRoute;
// Preserve next.route in case it did not get hoisted
attributes[ATTR_NEXT_ROUTE] = cleanRoute;
}
Expand All@@ -55,6 +56,7 @@ export function enhanceHandleRequestRootSpan(span: MutableRootSpan): void {
const routeBackfill = attributes[TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL];
if (typeof routeBackfill === 'string' && span.getName() !== 'GET /_app') {
span.setName(`${typeof method === 'string' ? method : 'GET'} ${routeBackfill}`);
attributes[HTTP_ROUTE] = attributes[HTTP_ROUTE] ?? routeBackfill;
}

const middlewareMatch =
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/test/config/withSentry.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import * as SentryCore from '@sentry/core';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import type { NextApiRequest, NextApiResponse } from 'next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
Expand DownExpand Up@@ -55,6 +55,7 @@ describe('withSentry', () => {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
[URL_FULL]: 'https://dogs.are.great/api/dogs?good=true',
[URL_PATH]: '/api/dogs',
[HTTP_ROUTE]: '/my-parameterized-route',
},
},
expect.any(Function),
Expand Down
53 changes: 51 additions & 2 deletions packages/nextjs/test/edge/withSentryAPI.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
import { afterAll, afterEach, describe, it, vi } from 'vitest';
import * as SentryCore from '@sentry/core';
import { HTTP_ROUTE, URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { wrapApiHandlerWithSentry } from '../../src/edge';

const origRequest = global.Request;
Expand DownExpand Up@@ -30,7 +33,7 @@ afterAll(() => {
});

afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
});

describe('wrapApiHandlerWithSentry', () => {
Expand All@@ -41,4 +44,50 @@ describe('wrapApiHandlerWithSentry', () => {

await wrappedFunction();
});

it('adds normalized request URL and route attributes to the active root span', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({ data: {} } as any);
const origFunction = vi.fn(() => new Response());
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(origFunction, parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456?good=true'));

expect(rootSpan.updateName).toHaveBeenCalledWith(`POST ${parameterizedRoute}`);
expect(rootSpan.setAttributes).toHaveBeenCalledWith({
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[URL_FULL]: 'https://dogs.are.great/user/123/post/456?good=true',
[URL_PATH]: '/user/123/post/456',
[HTTP_ROUTE]: parameterizedRoute,
});
});

it('replaces a concrete root span route with the parameterized route', async () => {
const rootSpan = {
updateName: vi.fn(),
setAttributes: vi.fn(),
};
vi.spyOn(SentryCore, 'getActiveSpan').mockReturnValueOnce({} as any);
vi.spyOn(SentryCore, 'getRootSpan').mockReturnValueOnce(rootSpan as any);
vi.spyOn(SentryCore, 'spanToJSON').mockReturnValueOnce({
data: { [HTTP_ROUTE]: '/user/123/post/456' },
} as any);
const parameterizedRoute = '/user/[userId]/post/[postId]';
const wrappedFunction = wrapApiHandlerWithSentry(() => new Response(), parameterizedRoute);

await wrappedFunction(new Request('https://dogs.are.great/user/123/post/456'));

expect(rootSpan.setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
[HTTP_ROUTE]: parameterizedRoute,
}),
);
});
});
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { describe, expect, it } from 'vitest';
import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_NAME, ATTR_NEXT_SPAN_TYPE } from '../../src/common/nextSpanAttributes';
Expand DownExpand Up@@ -48,6 +49,7 @@ describe('enhanceHandleRequestRootSpan', () => {
expect(getName()).toBe('GET /api/users/[id]');
expect(span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]).toBe('route');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/users/[id]');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/users/[id]');
});

it('strips trailing /route from app router route handler routes', () => {
Expand All@@ -64,6 +66,7 @@ describe('enhanceHandleRequestRootSpan', () => {

expect(getName()).toBe('POST /api/widgets');
expect(span.attributes[ATTR_NEXT_ROUTE]).toBe('/api/widgets');
expect(span.attributes[HTTP_ROUTE]).toBe('/api/widgets');
});

it('strips URL query and fragment from the segment name', () => {
Expand DownExpand Up@@ -105,6 +108,7 @@ describe('enhanceHandleRequestRootSpan', () => {
enhanceHandleRequestRootSpan(span);

expect(getName()).toBe('GET /posts/[slug]');
expect(span.attributes[HTTP_ROUTE]).toBe('/posts/[slug]');
});

it('does not apply the backfill for the special GET /_app transaction', () => {
Expand Down
Loading
Loading