Skip to content

Commit 9597447

Browse files
author
Luca Forstner
committed
feat(nextjs): Add instrumentation utility for server actions
1 parent b623a68 commit 9597447

File tree

2 files changed

+143
-0
lines changed

2 files changed

+143
-0
lines changed

packages/nextjs/src/common/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,5 @@ export { wrapApiHandlerWithSentryVercelCrons } from './wrapApiHandlerWithSentryV
4343
export { wrapMiddlewareWithSentry } from './wrapMiddlewareWithSentry';
4444

4545
export { wrapPageComponentWithSentry } from './wrapPageComponentWithSentry';
46+
47+
export { withSentryServerAction } from './withSentryServerAction';
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
import { addTracingExtensions, captureException, flush, getCurrentHub, runWithAsyncContext, trace } from '@sentry/core';
2+
import { addExceptionMechanism, logger, tracingContextFromHeaders } from '@sentry/utils';
3+
4+
import { platformSupportsStreaming } from './utils/platformSupportsStreaming';
5+
6+
interface Options {
7+
formData?: FormData;
8+
recordResponse?: boolean;
9+
}
10+
11+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
12+
export function withSentryServerAction<A extends (...args: any[]) => any>(
13+
serverActionName: string,
14+
callback: A,
15+
): Promise<ReturnType<A>>;
16+
17+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
18+
export function withSentryServerAction<A extends (...args: any[]) => any>(
19+
serverActionName: string,
20+
options: Options,
21+
callback: A,
22+
): Promise<ReturnType<A>>;
23+
24+
/**
25+
* Wraps a Next.js Server Action implementation with Sentry Error and Performance instrumentation.
26+
*/
27+
export function withSentryServerAction<A extends (...args: unknown[]) => unknown>(
28+
...args: [string, Options, A] | [string, A]
29+
): Promise<ReturnType<A>> {
30+
if (typeof args[1] === 'function') {
31+
const [serverActionName, callback] = args;
32+
return withSentryServerActionImplementation(serverActionName, {}, callback);
33+
} else {
34+
const [serverActionName, options, callback] = args;
35+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
36+
return withSentryServerActionImplementation(serverActionName, options, callback!);
37+
}
38+
}
39+
40+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
41+
async function withSentryServerActionImplementation<A extends (...args: any[]) => any>(
42+
serverActionName: string,
43+
options: Options,
44+
callback: A,
45+
): Promise<ReturnType<A>> {
46+
addTracingExtensions();
47+
return runWithAsyncContext(async () => {
48+
const hub = getCurrentHub();
49+
const sendDefaultPii = hub.getClient()?.getOptions().sendDefaultPii;
50+
51+
let sentryTraceHeader;
52+
let baggageHeader;
53+
const fullHeadersObject: Record<string, string> = {};
54+
try {
55+
// @ts-expect-errors Weird warnings about dynamic imports we do not care about.
56+
// eslint-disable-next-line import/no-unresolved
57+
const { headers }: { headers(): Headers } = await import('next/headers');
58+
const headersList = headers();
59+
sentryTraceHeader = headersList.get('sentry-trace') ?? undefined;
60+
baggageHeader = headersList.get('baggage');
61+
headersList.forEach((value, key) => {
62+
fullHeadersObject[key] = value;
63+
});
64+
} catch (e) {
65+
__DEBUG_BUILD__ &&
66+
logger.warn(
67+
"Sentry wasn't able to extract the tracing headers for a server action. Will not trace this request.",
68+
);
69+
}
70+
71+
const currentScope = hub.getScope();
72+
const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(
73+
sentryTraceHeader,
74+
baggageHeader,
75+
);
76+
currentScope.setPropagationContext(propagationContext);
77+
78+
let res;
79+
try {
80+
res = await trace(
81+
{
82+
op: 'function.server_action',
83+
name: `serverAction/${serverActionName}`,
84+
status: 'ok',
85+
...traceparentData,
86+
metadata: {
87+
source: 'route',
88+
dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,
89+
request: {
90+
headers: fullHeadersObject,
91+
},
92+
},
93+
},
94+
async span => {
95+
const result = await callback();
96+
97+
if (options.recordResponse !== undefined ? options.recordResponse : sendDefaultPii) {
98+
span?.setData('server_action_result', result);
99+
}
100+
101+
if (options.formData) {
102+
const formDataObject: Record<string, unknown> = {};
103+
options.formData.forEach((value, key) => {
104+
if (typeof value === 'string') {
105+
formDataObject[key] = value;
106+
} else {
107+
formDataObject[key] = '[non-string value]';
108+
}
109+
});
110+
span?.setData('server_action_form_data', formDataObject);
111+
}
112+
113+
return result;
114+
},
115+
error => {
116+
captureException(error, scope => {
117+
scope.addEventProcessor(event => {
118+
addExceptionMechanism(event, {
119+
handled: false,
120+
});
121+
return event;
122+
});
123+
124+
return scope;
125+
});
126+
},
127+
);
128+
} finally {
129+
if (!platformSupportsStreaming()) {
130+
// Lambdas require manual flushing to prevent execution freeze before the event is sent
131+
await flush(1000);
132+
}
133+
134+
if (process.env.NEXT_RUNTIME === 'edge') {
135+
void flush();
136+
}
137+
}
138+
139+
return res;
140+
});
141+
}

0 commit comments

Comments
 (0)