Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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 number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { AppLoadContext, EntryContext } from 'react-router';
import { ServerRouter } from 'react-router';
const ABORT_DELAY = 5_000;

export default function handleRequest(
function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
Expand Down Expand Up @@ -60,6 +60,8 @@ export default function handleRequest(
});
}

export default Sentry.sentryHandleRequest(handleRequest);

import { type HandleErrorFunction } from 'react-router';

export const handleError: HandleErrorFunction = (error, { request }) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import { APP_NAME } from '../constants';
test.describe('servery - performance', () => {
test('should send server transaction on pageload', async ({ page }) => {
const txPromise = waitForTransaction(APP_NAME, async transactionEvent => {
// todo: should be GET /performance
return transactionEvent.transaction === 'GET *';
return transactionEvent.transaction === 'GET performance';
});

await page.goto(`/performance`);
Expand All @@ -30,8 +29,7 @@ test.describe('servery - performance', () => {
spans: expect.any(Array),
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
// todo: should be GET /performance
transaction: 'GET *',
transaction: 'GET performance',
type: 'transaction',
transaction_info: { source: 'route' },
platform: 'node',
Expand All @@ -58,8 +56,7 @@ test.describe('servery - performance', () => {

test('should send server transaction on parameterized route', async ({ page }) => {
const txPromise = waitForTransaction(APP_NAME, async transactionEvent => {
// todo: should be GET /performance/with/:param
return transactionEvent.transaction === 'GET *';
return transactionEvent.transaction === 'GET performance/with/:param';
});

await page.goto(`/performance/with/some-param`);
Expand All @@ -83,8 +80,7 @@ test.describe('servery - performance', () => {
spans: expect.any(Array),
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
// todo: should be GET /performance/with/:param
transaction: 'GET *',
transaction: 'GET performance/with/:param',
type: 'transaction',
transaction_info: { source: 'route' },
platform: 'node',
Expand Down
1 change: 1 addition & 0 deletions packages/react-router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"@sentry/core": "9.9.0",
"@sentry/node": "9.9.0",
"@sentry/vite-plugin": "^3.2.0",
"@opentelemetry/semantic-conventions": "^1.30.0",
"glob": "11.0.1"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions packages/react-router/src/server/attributes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const SENTRY_PARAMETERIZED_ROUTE = 'sentry.parameterized_route';
1 change: 1 addition & 0 deletions packages/react-router/src/server/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from '@sentry/node';

export { init } from './sdk';
export { sentryHandleRequest } from './sentryHandleRequest';
28 changes: 27 additions & 1 deletion packages/react-router/src/server/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { applySdkMetadata, setTag } from '@sentry/core';
import { applySdkMetadata, logger, SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD, setTag } from '@sentry/core';
import type { NodeClient, NodeOptions } from '@sentry/node';
import { init as initNodeSdk } from '@sentry/node';
import { DEBUG_BUILD } from '../common/debug-build';
import { SENTRY_PARAMETERIZED_ROUTE } from './attributes';
import { ATTR_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';

/**
* Initializes the server side of the React Router SDK
Expand All @@ -10,11 +13,34 @@ export function init(options: NodeOptions): NodeClient | undefined {
...options,
};

DEBUG_BUILD && logger.log('Initializing SDK...');

applySdkMetadata(opts, 'react-router', ['react-router', 'node']);

const client = initNodeSdk(opts);

setTag('runtime', 'node');

client?.on('preprocessEvent', event => {
if (event.type === 'transaction' && event.transaction) {
// Check if the transaction name matches an HTTP method with a wildcard route (e.g. "GET *")
if (event.transaction.match(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|TRACE|CONNECT) \*$/)) {
const traceData = event.contexts?.trace?.data;
if (traceData) {
// Get the parameterized route that was stored earlier by our wrapped handler (e.g. "/users/:id")
const paramRoute = traceData[SENTRY_PARAMETERIZED_ROUTE];
if (paramRoute) {
traceData[ATTR_HTTP_ROUTE] = paramRoute;
const method = traceData[SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD] || traceData['http.method'];
if (method) {
event.transaction = `${method} ${paramRoute}`;
}
}
}
}
}
});

DEBUG_BUILD && logger.log('SDK successfully initialized');
return client;
}
38 changes: 38 additions & 0 deletions packages/react-router/src/server/sentryHandleRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { AppLoadContext, EntryContext } from 'react-router';
import { SENTRY_PARAMETERIZED_ROUTE } from './attributes';
import { getRootSpan, getActiveSpan } from '@sentry/core';

type OriginalHandleRequest = (
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
routerContext: EntryContext,
loadContext: AppLoadContext,
) => Promise<unknown>;

/**
* Wraps the original handleRequest function to add Sentry instrumentation.
*
* @param originalHandle - The original handleRequest function to wrap
* @returns A wrapped version of the handle request function with Sentry instrumentation
*/
export function sentryHandleRequest(originalHandle: OriginalHandleRequest): OriginalHandleRequest {
return async function sentryInstrumentedHandleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
routerContext: EntryContext,
loadContext: AppLoadContext,
) {
const parameterizedPath =
routerContext?.staticHandlerContext?.matches?.[routerContext.staticHandlerContext.matches.length - 1]?.route.path;
if (parameterizedPath) {
const activeSpan = getActiveSpan();
if (activeSpan) {
const rootSpan = getRootSpan(activeSpan);
rootSpan.setAttribute(SENTRY_PARAMETERIZED_ROUTE, parameterizedPath);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason we don't update the name of the root span here directly?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried this, but it got overwritten somehow

}
}
return originalHandle(request, responseStatusCode, responseHeaders, routerContext, loadContext);
};
}
Loading