Skip to content

feat(nextjs): Add instrumentation utility for server actions #9553

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 3 commits into from
Nov 14, 2023
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 number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as Sentry from '@sentry/nextjs';
import { headers } from 'next/headers';

export default function ServerComponent() {
async function myServerAction(formData: FormData) {
'use server';
return await Sentry.withServerActionInstrumentation(
'myServerAction',
{ formData, headers: headers(), recordResponse: true },
async () => {
await fetch('http://example.com/');
return { city: 'Vienna' };
},
);
}

return (
// @ts-ignore
<form action={myServerAction}>
<input type="text" defaultValue={'some-default-value'} name="some-text-value" />
<button type="submit">Run Action</button>
</form>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const { withSentryConfig } = require('@sentry/nextjs');
const moduleExports = {
experimental: {
appDir: true,
serverActions: true,
},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { test, expect } from '@playwright/test';
import { waitForTransaction } from '../event-proxy-server';
import axios, { AxiosError } from 'axios';

const packageJson = require('../package.json');

const authToken = process.env.E2E_TEST_AUTH_TOKEN;
const sentryTestOrgSlug = process.env.E2E_TEST_SENTRY_ORG_SLUG;
const sentryTestProject = process.env.E2E_TEST_SENTRY_TEST_PROJECT;
Expand Down Expand Up @@ -112,3 +114,26 @@ if (process.env.TEST_ENV === 'production') {
expect((await serverComponentTransactionPromise).contexts?.trace?.status).toBe('not_found');
});
}

test('Should send a transaction for instrumented server actions', async ({ page }) => {
const nextjsVersion = packageJson.dependencies.next;
const nextjsMajor = Number(nextjsVersion.split('.')[0]);
test.skip(!isNaN(nextjsMajor) && nextjsMajor < 14, 'only applies to nextjs apps >= version 14');

const serverComponentTransactionPromise = waitForTransaction('nextjs-13-app-dir', async transactionEvent => {
return transactionEvent?.transaction === 'serverAction/myServerAction';
});

await page.goto('/server-action');
await page.getByText('Run Action').click();

expect(await serverComponentTransactionPromise).toBeDefined();
expect((await serverComponentTransactionPromise).contexts?.trace?.data?.['server_action_form_data']).toEqual(
expect.objectContaining({ 'some-text-value': 'some-default-value' }),
);
expect((await serverComponentTransactionPromise).contexts?.trace?.data?.['server_action_result']).toEqual({
city: 'Vienna',
});

expect(Object.keys((await serverComponentTransactionPromise).request?.headers || {}).length).toBeGreaterThan(0);
});
2 changes: 2 additions & 0 deletions packages/nextjs/src/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ export { wrapApiHandlerWithSentryVercelCrons } from './wrapApiHandlerWithSentryV
export { wrapMiddlewareWithSentry } from './wrapMiddlewareWithSentry';

export { wrapPageComponentWithSentry } from './wrapPageComponentWithSentry';

export { withServerActionInstrumentation } from './withServerActionInstrumentation';
139 changes: 139 additions & 0 deletions packages/nextjs/src/common/withServerActionInstrumentation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { addTracingExtensions, captureException, flush, getCurrentHub, runWithAsyncContext, trace } from '@sentry/core';
import { addExceptionMechanism, logger, tracingContextFromHeaders } from '@sentry/utils';

import { platformSupportsStreaming } from './utils/platformSupportsStreaming';

interface Options {
formData?: FormData;
// TODO: Whenever we decide to drop support for Next.js <= 12 we can automatically pick up the headers becauase "next/headers" will be resolvable.
headers?: Headers;
recordResponse?: boolean;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function withServerActionInstrumentation<A extends (...args: any[]) => any>(
serverActionName: string,
callback: A,
): Promise<ReturnType<A>>;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function withServerActionInstrumentation<A extends (...args: any[]) => any>(
serverActionName: string,
options: Options,
callback: A,
): Promise<ReturnType<A>>;

/**
* Wraps a Next.js Server Action implementation with Sentry Error and Performance instrumentation.
*/
export function withServerActionInstrumentation<A extends (...args: unknown[]) => unknown>(
...args: [string, Options, A] | [string, A]
): Promise<ReturnType<A>> {
if (typeof args[1] === 'function') {
const [serverActionName, callback] = args;
return withServerActionInstrumentationImplementation(serverActionName, {}, callback);
} else {
const [serverActionName, options, callback] = args;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return withServerActionInstrumentationImplementation(serverActionName, options, callback!);
}
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function withServerActionInstrumentationImplementation<A extends (...args: any[]) => any>(
serverActionName: string,
options: Options,
callback: A,
): Promise<ReturnType<A>> {
addTracingExtensions();
return runWithAsyncContext(async () => {
const hub = getCurrentHub();
const sendDefaultPii = hub.getClient()?.getOptions().sendDefaultPii;

let sentryTraceHeader;
let baggageHeader;
const fullHeadersObject: Record<string, string> = {};
try {
sentryTraceHeader = options.headers?.get('sentry-trace') ?? undefined;
baggageHeader = options.headers?.get('baggage');
options.headers?.forEach((value, key) => {
fullHeadersObject[key] = value;
});
} catch (e) {
__DEBUG_BUILD__ &&
logger.warn(
"Sentry wasn't able to extract the tracing headers for a server action. Will not trace this request.",
);
}

const currentScope = hub.getScope();
const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(
sentryTraceHeader,
baggageHeader,
);
currentScope.setPropagationContext(propagationContext);

let res;
try {
res = await trace(
{
op: 'function.server_action',
name: `serverAction/${serverActionName}`,
status: 'ok',
...traceparentData,
metadata: {
source: 'route',
dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,
request: {
headers: fullHeadersObject,
},
},
},
async span => {
const result = await callback();

if (options.recordResponse !== undefined ? options.recordResponse : sendDefaultPii) {
span?.setData('server_action_result', result);
}

if (options.formData) {
const formDataObject: Record<string, unknown> = {};
options.formData.forEach((value, key) => {
if (typeof value === 'string') {
formDataObject[key] = value;
} else {
formDataObject[key] = '[non-string value]';
}
});
span?.setData('server_action_form_data', formDataObject);
}

return result;
},
error => {
captureException(error, scope => {
scope.addEventProcessor(event => {
addExceptionMechanism(event, {
handled: false,
});
return event;
});

return scope;
});
},
);
} finally {
if (!platformSupportsStreaming()) {
// Lambdas require manual flushing to prevent execution freeze before the event is sent
await flush(1000);
}

if (process.env.NEXT_RUNTIME === 'edge') {
void flush();
}
}

return res;
});
}