Skip to content

Commit 043013f

Browse files
author
Luca Forstner
committed
feat(node): Add Sentry tRPC middleware
1 parent 30bba1f commit 043013f

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

packages/node/src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ const INTEGRATIONS = {
6565

6666
export { INTEGRATIONS as Integrations, Handlers };
6767

68+
export { sentryTrpcMiddleware } from './trpc';
69+
6870
// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like
6971
// @sentry/core. If we don't do this, browser bundlers will have troubles resolving `require('domain')`.
7072
const carrier = getMainCarrier();

packages/node/src/trpc.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { getCurrentHub } from '@sentry/core';
2+
import { normalize } from '@sentry/utils';
3+
4+
interface SentryTrpcMiddlewareOptions {
5+
attachRpcInput?: boolean;
6+
}
7+
8+
interface TrpcMiddlewareArguments<T> {
9+
path: string;
10+
type: 'query' | 'mutation' | 'subscription';
11+
next: () => Promise<T>;
12+
rawInput: unknown;
13+
}
14+
15+
/**
16+
* Sentry tRPC middleware that names the handling transaction after the called procedure.
17+
*
18+
* Use the Sentry tRPC middleware in combination with the Sentry server integration. (e.g. express integration or
19+
* Next.js SDK)
20+
*/
21+
export async function sentryTrpcMiddleware(options: SentryTrpcMiddlewareOptions) {
22+
return async function <T>({ path, type, next, rawInput }: TrpcMiddlewareArguments<T>): Promise<T> {
23+
const hub = getCurrentHub();
24+
const clientOptions = hub.getClient()?.getOptions();
25+
const sentryTransaction = hub.getScope()?.getTransaction();
26+
27+
if (sentryTransaction) {
28+
sentryTransaction.setName(`${path}()`, 'route');
29+
sentryTransaction.op = 'rpc.server';
30+
31+
const trpcData: Record<string, unknown> = {
32+
procedureType: type,
33+
};
34+
35+
if (options.attachRpcInput !== undefined ? options.attachRpcInput : clientOptions?.sendDefaultPii) {
36+
trpcData.procedureInput = normalize(rawInput);
37+
}
38+
39+
sentryTransaction.setData('trpc', trpcData);
40+
}
41+
42+
return await next();
43+
};
44+
}

0 commit comments

Comments
 (0)