Skip to content

feat(node): Add Sentry tRPC middleware #7511

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Mar 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions packages/node/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
extractTraceparentData,
isString,
logger,
normalize,
} from '@sentry/utils';
import * as domain from 'domain';
import type * as http from 'http';
Expand Down Expand Up @@ -315,6 +316,49 @@ export function errorHandler(options?: {
};
}

interface SentryTrpcMiddlewareOptions {
/** Whether to include procedure inputs in reported events. Defaults to `false`. */
attachRpcInput?: boolean;
Copy link
Member

Choose a reason for hiding this comment

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

m: can we add a doc string?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

👍 8ab4c72

}

interface TrpcMiddlewareArguments<T> {
path: string;
type: 'query' | 'mutation' | 'subscription';
next: () => T;
rawInput: unknown;
}

/**
* Sentry tRPC middleware that names the handling transaction after the called procedure.
*
* Use the Sentry tRPC middleware in combination with the Sentry server integration,
* e.g. Express Request Handlers or Next.js SDK.
*/
export async function trpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) {
return function <T>({ path, type, next, rawInput }: TrpcMiddlewareArguments<T>): T {
const hub = getCurrentHub();
const clientOptions = hub.getClient()?.getOptions();
const sentryTransaction = hub.getScope()?.getTransaction();

if (sentryTransaction) {
sentryTransaction.setName(`trcp/${path}`, 'route');
sentryTransaction.op = 'rpc.server';

const trpcContext: Record<string, unknown> = {
procedure_type: type,
};

if (options.attachRpcInput !== undefined ? options.attachRpcInput : clientOptions?.sendDefaultPii) {
trpcContext.input = normalize(rawInput);
}

sentryTransaction.setContext('trpc', trpcContext);
}

return next();
};
}

// TODO (v8 / #5257): Remove this
// eslint-disable-next-line deprecation/deprecation
export type { ParseRequestOptions, ExpressRequest } from './requestDataDeprecated';
Expand Down