Skip to content

docs(js): move API-related content from Manual Setup to APIs page #13327

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 7 commits into from
Apr 29, 2025
128 changes: 119 additions & 9 deletions docs/platforms/javascript/common/apis.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ Messages show up as issues on your issue stream, with the message as the issue n
You cannot search these, but they are viewable on the issue page - if you
need to be able to filter for certain data, use [tags](./#setTag) instead.

There are no restrictions on context name. In the context object, all keys are allowed except for `type`, which is used internally.
There are no restrictions on context name. In the context object, all keys are allowed except for `type`, which is used internally.

By default, Sentry SDKs normalize nested structured context data up to three levels deep.
Any data beyond this depth will be trimmed and marked using its type instead.
Expand All @@ -341,13 +341,14 @@ Learn more about conventions for common contexts in the [contexts interface deve
<Expandable title='Example'>
Context data is structured and can contain any data you want:

```javascript
Sentry.setContext("character", {
name: "Mighty Fighter",
age: 19,
attack_type: "melee",
});
```
```javascript
Sentry.setContext("character", {
name: "Mighty Fighter",
age: 19,
attack_type: "melee",
});
```

</Expandable>

</SdkApi>
Expand Down Expand Up @@ -426,7 +427,6 @@ Learn more about conventions for common contexts in the [contexts interface deve

</Expandable>


<PlatformCategorySection supported={["server"]}>
<Expandable title="Setting The User For the Current Request ">
<PlatformSection notSupported={['javascript.bun', 'javascript.cloudflare', 'javascript.deno', 'javascript.react-router', 'javascript.aws-lambda', 'javascript.azure-functions', 'javascript.gcp-functions']}>
Expand Down Expand Up @@ -1077,3 +1077,113 @@ parameters={[
Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.
</SdkApi>
</PlatformCategorySection>

<PlatformSection supported={["javascript.nextjs"]}>
## Server Actions

<SdkApi
name="withServerActionInstrumentation"
signature="function withServerActionInstrumentation(serverActionName: string, options?: Options, callback: A): Promise<ReturnType<A>>"
Copy link
Contributor

Choose a reason for hiding this comment

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

I think it makes more sense to format this with line breaks similar to the example before it, just for the sake of readability, something like:

function withServerActionInstrumentation(
  serverActionName: string,
  options?: Options,
  callback: A,
): Promise<ReturnType<A>>;

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Good idea, thanks!
I've formatted all the functions I've added so they are more readable now 👍

>
To instrument Next.js Server Actions, wrap their content in `withServerActionInstrumentation`, along with a name to describe your server action.
You can optionally pass form data and headers to record them, and configure the wrapper to record the Server Action responses.

<Expandable title="Examples">
```tsx
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", // The name you want to associate this Server Action with in Sentry
{
formData, // Optionally pass in the form data
headers: await headers(), // Optionally pass in headers
recordResponse: true, // Optionally record the server action response
},
async () => {
// ... Your Server Action code

return { name: "John Doe" };
}
);
}

return (
<form action={myServerAction}>
<input type="text" name="some-input-value" />
<button type="submit">Run Action</button>
</form>
);
}
```

</Expandable>
</SdkApi>

## Route and Data Fetching Instrumentation

<SdkApi
name="wrapApiHandlerWithSentry"
signature="function wrapApiHandlerWithSentry(apiHandler: NextApiHandler, parameterizedRoute: string): NextApiHandler"
>
Instrument the provided API route handler with Sentry for error and
performance monitoring. This function wraps the handler exported from the
user's API page route file (which may or may not already be wrapped with
`withSentry`).
</SdkApi>

<SdkApi
name="wrapGetInitialPropsWithSentry "
signature="function wrapGetInitialPropsWithSentry(origGetInitialProps: GetInitialProps): GetInitialProps"
>
Instrument a `getInitialProps` function with Sentry error and performance
monitoring by creating and returning a wrapped version of the function.
</SdkApi>

<SdkApi
name="wrapGetServerSidePropsWithSentry "
signature="function wrapGetServerSidePropsWithSentry(origGetInitialProps: GetInitialProps, parameterizedRoute: string): GetServerSideProps"
>
Instrument a `getServerSideProps` function with Sentry error and performance
monitoring by creating and returning a wrapped version of the function.
</SdkApi>

<SdkApi
name="wrapGetStaticPropsWithSentry "
signature="function wrapGetStaticPropsWithSentry(origGetStaticPropsa: GetStaticProps<Props>, _parameterizedRoute: string): GetStaticProps<Props>"
>
Instrument a `getStaticProps` function with Sentry error and performance
monitoring by creating and returning a wrapped version of the function.
</SdkApi>

<SdkApi
name="wrapErrorGetInitialPropsWithSentry "
signature="function wrapErrorGetInitialPropsWithSentry(origErrorGetInitialProps: ErrorGetInitialProps): ErrorGetInitialProps"
>
Instrument a `getInitialProps` function in a custom error page ("_error.js")
with Sentry error and performance monitoring by creating and returning a
wrapped version of the function.
</SdkApi>

<SdkApi
name="wrapAppGetInitialPropsWithSentry "
signature="function wrapAppGetInitialPropsWithSentry(origAppGetInitialProps: AppGetInitialProps): AppGetInitialProps"
>
Instrument a `getInitialProps` function in a custom app ("_app.js") with
Sentry error and performance monitoring by creating and returning a wrapped
version of the function.
</SdkApi>

<SdkApi
name="wrapDocumentGetInitialPropsWithSentry "
signature="function wrapDocumentGetInitialPropsWithSentry(origDocumentGetInitialProps: DocumentGetInitialProps): DocumentGetInitialProps"
>
Instrument a `getInitialProps` function in a custom document ("_document.js")
with Sentry error and performance monitoring by creating and returning a
wrapped version of the function.
</SdkApi>

</PlatformSection>
169 changes: 16 additions & 153 deletions docs/platforms/javascript/guides/nextjs/manual-setup.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,14 @@ Sentry.init({
tracesSampleRate: 1.0,
// Replay may only be enabled for the client-side
integrations: [Sentry.replayIntegration()],

// Capture Replay for 10% of all sessions,
// plus for 100% of sessions with an error
// Learn more at
// https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,

// Note: if you want to override the automatic release value, do not set a
// `release` value here - use the environment variable `SENTRY_RELEASE`, so
// that it will also get attached to your source maps
Expand Down Expand Up @@ -195,6 +195,15 @@ export async function register() {
file.
</Alert>

<Expandable title="Opt out of Sentry SDK bundling on client- or server-side.">
If you want the Sentry SDK to be available on the server side and not on the
client side, simply delete `instrumentation-client.(js|ts)`. This will prevent
webpack from pulling in the Sentry-related files when generating the browser
bundle. Similarly, if you want to opt out of server-side SDK bundling, delete
the `sentry.server.config.js` and `sentry.edge.config.js` files. Make sure to
remove any imports of these files from `instrumentation.ts`.
</Expandable>

## Step 3: Capture React Render Errors

To capture React render errors, you need to add error components for the App Router and the Pages Router.
Expand Down Expand Up @@ -350,46 +359,7 @@ CustomErrorComponent.getInitialProps = async (contextData) => {
export default CustomErrorComponent;
```

## Step 4: Instrument Next.js Server Actions (Optional)

_Requires `@sentry/nextjs` SDK version `7.81.0` or newer._

To instrument Next.js Server Actions, wrap their content in `withServerActionInstrumentation`, along with a name to describe your server action.

You can optionally pass form data and headers to record them, and configure the wrapper to record the Server Action responses:

```tsx
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", // The name you want to associate this Server Action with in Sentry
{
formData, // Optionally pass in the form data
headers: await headers(), // Optionally pass in headers
recordResponse: true, // Optionally record the server action response
},
async () => {
// ... Your Server Action code

return { name: "John Doe" };
}
);
}

return (
<form action={myServerAction}>
<input type="text" name="some-input-value" />
<button type="submit">Run Action</button>
</form>
);
}
```

## Step 5: Add Readable Stack Traces With Source Maps (Optional)
## Step 4: Add Readable Stack Traces With Source Maps (Optional)

Sentry can automatically provide readable stack traces for errors using source maps, requiring a Sentry auth token.

Expand Down Expand Up @@ -431,7 +401,7 @@ Make sure to keep your auth token secret and out of version control.

</Alert>

## Step 6: Avoid Ad Blockers With Tunneling (Optional)
## Step 5: Avoid Ad Blockers With Tunneling (Optional)

You can prevent ad blockers from blocking Sentry events using tunneling. Use the `tunnelRoute` option to add an API endpoint in your application that forwards Sentry events to Sentry servers.

Expand Down Expand Up @@ -461,114 +431,7 @@ module.exports = withSentryConfig(nextConfig, {
negative matcher to your middleware like `(?!monitoring-tunnel)`.
</Alert>

## Step 7: Configure Server-side Auto-instrumentation (Optional)

The SDK will automatically instrument API routes and server-side [Next.js data fetching methods](https://nextjs.org/docs/basic-features/data-fetching/overview) with error and tracing.

### Disable API Route, Middleware and Data Fetching Auto-instrumentation Entirely

To disable the automatic instrumentation of API route handlers and server-side data fetching functions, set the `autoInstrumentServerFunctions` to `false`.

```javascript {tabTitle:ESM} {filename:next.config.mjs}
export default withSentryConfig(nextConfig, {
autoInstrumentServerFunctions: false,
});
```

```javascript {tabTitle:CJS} {filename:next.config.js}
module.exports = withSentryConfig(nextConfig, {
autoInstrumentServerFunctions: false,
});
```

With this option, under the hood, the SDK is using a webpack loader to wrap all your API route handlers and data fetching methods.

### Opt In to Auto-instrumentation on Specific Routes

If the automatic instrumentation doesn't work for your use case, you can turn it off globally and choose to only wrap specific API route handlers or data fetching functions instead.

For API routes, use the `wrapApiHandlerWithSentry` function:

```javascript {filename:pages/api/*}
import { wrapApiHandlerWithSentry } from "@sentry/nextjs";

const handler = (req, res) => {
res.status(200).json({ name: "John Doe" });
};

export default wrapApiHandlerWithSentry(handler, "/api/myRoute");
```

```typescript {filename:pages/api/*}
import type { NextApiRequest, NextApiResponse } from "next";
import { wrapApiHandlerWithSentry } from "@sentry/nextjs";

const handler = (req: NextApiRequest, res: NextApiResponse) => {
res.status(200).json({ name: "John Doe" });
};

export default wrapApiHandlerWithSentry(handler, "/api/myRoute");
```

For data fetching methods, use the following functions:

- `wrapGetInitialPropsWithSentry` for `getInitialProps`
- `wrapGetServerSidePropsWithSentry` for `getServerSideProps`
- `wrapGetStaticPropsWithSentry` for `getStaticProps`
- `wrapErrorGetInitialPropsWithSentry` for `getInitialProps` in [custom Error pages](https://nextjs.org/docs/advanced-features/custom-error-page)
- `wrapAppGetInitialPropsWithSentry` for `getInitialProps` in [custom `App` components](https://nextjs.org/docs/advanced-features/custom-app)
- `wrapDocumentGetInitialPropsWithSentry` for `getInitialProps` in [custom `Document` components](https://nextjs.org/docs/advanced-features/custom-document)

### Opt Out of Auto-instrumentation on Specific Routes

If you want auto-instrumentation to apply by default, but want to exclude certain routes, use the `excludeServerRoutes` option:

```javascript {tabTitle:ESM} {filename:next.config.mjs}
export default withSentryConfig(nextConfig, {
excludeServerRoutes: [
"/some/excluded/route",
"/excluded/route/with/[parameter]",
/^\/route\/beginning\/with\/some\/prefix/,
/\/routeContainingASpecificPathSegment\/?/,
],
});
```

```javascript {tabTitle:CJS} {filename:next.config.js}
module.exports = withSentryConfig(nextConfig, {
excludeServerRoutes: [
"/some/excluded/route",
"/excluded/route/with/[parameter]",
/^\/route\/beginning\/with\/some\/prefix/,
/\/routeContainingASpecificPathSegment\/?/,
],
});
```

Excluded routes can be specified either as regexes or strings. When using a string, make sure that it matches the route exactly, and has a leading slash but no trailing one.

### Opt Out of Auto-instrumentation on Middleware

To disable the automatic instrumentation of Next.js middleware, set the `autoInstrumentMiddleware` option to `false`.

```javascript {tabTitle:ESM} {filename:next.config.mjs}
export default withSentryConfig(nextConfig, {
autoInstrumentMiddleware: false,
});
```

```javascript {tabTitle:CJS} {filename:next.config.js}
module.exports = withSentryConfig(nextConfig, {
autoInstrumentMiddleware: false,
});
```

### Opt Out of Sentry SDK bundling in Client- or Server-Side

If you want the Sentry SDK to be available in your server-side and not in client-side, you can simply delete `instrumentation-client.(js|ts)`. This will prevent webpack from pulling in the Sentry related files when generating the browser bundle.
Similarly, to opt out of server-side SDK bundling, you can simply delete the `sentry.server.config.js` and `sentry.edge.config.js` files. Make sure to remove any imports of these files from `instrumentation.ts`.

## Step 8: Instrument Vercel Cron Jobs (Optional)
## Step 6: Instrument Vercel Cron Jobs (Optional)

You can automatically create [Cron Monitors](/product/crons/) in Sentry if you have configured [Vercel cron jobs](https://vercel.com/docs/cron-jobs).

Expand All @@ -592,7 +455,7 @@ Automatic Vercel cron jobs instrumentation currently only supports the Pages Rou

</Alert>

## Step 9: Capture React Component Names (Optional)
## Step 7: Capture React Component Names (Optional)

You can capture React component names to see which component a user clicked on in Sentry features like Session Replay.
Update `withSentryConfig` in your `next.config.(js|mjs)` file with the following option:
Expand All @@ -613,7 +476,7 @@ module.exports = withSentryConfig(nextConfig, {
});
```

## Step 10: Verify
## Step 8: Verify

<Include name="nextjs-turbopack-warning-expandable.mdx" />

Expand Down