From b0e70c838f8496ceced8fecdd14e7e73080c3470 Mon Sep 17 00:00:00 2001 From: Sarah Mischinger Date: Tue, 11 Feb 2025 10:59:25 +0100 Subject: [PATCH 01/10] commit first rough draft of page for a first review of structure --- .../javascript/guides/nextjs/manual-setup.mdx | 562 ++++++------------ 1 file changed, 191 insertions(+), 371 deletions(-) diff --git a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx index f7ef7a32be748..5a2fceebdbb18 100644 --- a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx +++ b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx @@ -1,12 +1,18 @@ --- -title: Manual Setup +title: "Quickstart: Manual Setup" sidebar_order: 1 -description: "Learn how to set up the SDK manually." +description: "Learn how to manually set up and configure Sentry in your Next.js application, capture your first errors, and view them in Sentry." --- -If you can't (or prefer not to) run the [automatic setup](/platforms/javascript/guides/nextjs/#install), you can follow the instructions below to configure your application. +## Prerequisites -## Installation +- A Sentry [account](https://sentry.io/signup/) and [project](https://docs.sentry.io/product/projects/) +- Be logged in to your Sentry account to have your project's data pre-filled (recommended) +- Your application up and running + +## Step 1: Install + +Run the following command for your preferred package manager to add the Sentry SDK to your application: ```bash {tabTitle:npm} npm install @sentry/nextjs --save @@ -20,13 +26,38 @@ yarn add @sentry/nextjs pnpm add @sentry/nextjs ``` -If you're updating your Sentry SDK to the latest version, check out our [migration guide](https://github.com/getsentry/sentry-javascript/blob/master/MIGRATION.md) to learn more about breaking changes. +### Choose Your Sentry Features + +Select the features you want to set up in your application, in addition to error monitoring, using the checkboxes below. This guide will then adjust its content to provide you with the necessary information. + + + +- [**Issues**](/product/issues) (always enabled): Sentry's core error monitoring product that automatically reports errors, + uncaught exceptions, and unhandled rejections. If you have something that + looks like an exception, Sentry can capture it. +- [**Tracing**](/product/tracing): Track software performance while seeing the + impact of errors across multiple systems. For example, distributed tracing + allows you to follow a request from the frontend to the backend and back. +- [**Session Replay**](/product/explore/session-replay/web): + Get to the root cause of an issue faster by viewing a video-like reproduction + of what was happening in the user's browser before, during, and after the + problem. + + + +You can add or remove features at any time, but setting them up now will save you the effort of configuring them manually later. -## Extend your Next.js Configuration + -Use `withSentryConfig` to extend the default Next.js options. This will apply instrumentation to your application. +## Step 2: Configure -Include the following in your `next.config.js` or `next.config.mjs`: +### Apply Instrumentation to Your App + +To apply instrumentation to your application, use `withSentryConfig` to extend your app's default Next.js options. + +Update your `next.config.js` or `next.config.mjs` file with the following: ```JavaScript {tabTitle:CJS} {filename:next.config.js} const { withSentryConfig } = require("@sentry/nextjs"); @@ -40,10 +71,17 @@ module.exports = withSentryConfig(nextConfig, { org: "___ORG_SLUG___", project: "___PROJECT_SLUG___", - // An auth token is required for uploading source maps. - authToken: process.env.SENTRY_AUTH_TOKEN, + // Only print logs for uploading source maps in CI + // Set to `false` to surpress logs + silent: !process.env.CI, + + // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client-side errors will fail. + tunnelRoute: "/monitoring", - silent: false, // Can be used to suppress logs + // Automatically tree-shake Sentry logger statements to reduce bundle size + disableLogger: true, }); ``` @@ -59,28 +97,37 @@ export default withSentryConfig(nextConfig, { org: "___ORG_SLUG___", project: "___PROJECT_SLUG___", - // An auth token is required for uploading source maps. - authToken: process.env.SENTRY_AUTH_TOKEN, + // Only print logs for uploading source maps in CI + // Set to `false` to surpress logs + silent: !process.env.CI, + + // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client-side errors will fail. + tunnelRoute: "/monitoring", - silent: false, // Can be used to suppress logs + // Automatically tree-shake Sentry logger statements to reduce bundle size + disableLogger: true, }); ``` -### Extend Sentry Webpack Plugin Options -`withSentryConfig` uses a [custom Webpack plugin](https://www.npmjs.com/package/@sentry/webpack-plugin) to manage your sourcemaps and releases under the hood. If `withSentryConfig` does not provide the option you need to modify, you may override the `sentryWebpackPluginOptions` directly via `unstable_sentryWebpackPluginOptions`. - - - Note that this option is unstable and its API may include breaking changes in any release. - - + + You might notice that ad blockers sometimes block Sentry events, which you can + circumvent using tunneling. Setting the `tunnelRoute` option will add an API + endpoint to your application that is used to forward Sentry events to the + Sentry servers. + -## Create Initialization Config Files +### Initialize Sentry Client-Side and Server-Side SDKs Create three files in the root directory of your Next.js application: `sentry.client.config.js`, `sentry.server.config.js` and `sentry.edge.config.js`. In these files, add your initialization code for the client-side SDK and server-side SDK, respectively. We've included some examples below. -Please note that there are slight differences between these files since they run in different places (browser, server, edge), so copy them carefully! + + There are slight differences between these files since they run in different + places (browser, server, edge), so copy them carefully! + -```javascript {tabTitle:Client} {filename:sentry.client.config.(js|ts)} +```javascript {tabTitle:Client} {filename:sentry.client.config.(js|ts)} {"onboardingOptions": {"performance": "8-13", "session-replay": "5-6, 15-20"}} import * as Sentry from "@sentry/nextjs"; Sentry.init({ @@ -110,7 +157,7 @@ Sentry.init({ }); ``` -```javascript {tabTitle:Server} {filename:sentry.server.config.(js|ts)} +```javascript {tabTitle:Server} {filename:sentry.server.config.(js|ts)} {"onboardingOptions": {"performance": "6-11"}} import * as Sentry from "@sentry/nextjs"; Sentry.init({ @@ -131,7 +178,7 @@ Sentry.init({ }); ``` -```javascript {tabTitle:Edge} {filename:sentry.edge.config.(js|ts)} +```javascript {tabTitle:Edge} {filename:sentry.edge.config.(js|ts)} {"onboardingOptions": {"performance": "6-11"}} import * as Sentry from "@sentry/nextjs"; Sentry.init({ @@ -152,7 +199,14 @@ Sentry.init({ }); ``` -We recommend you include your DSN directly in these three files. Alternatively you can pass the DSN via a _public_ environment variable like `NEXT_PUBLIC_SENTRY_DSN`. + + We recommend you include your [Data Source + Name](/concepts/key-terms/dsn-explainer/) (DSN) directly in these three files. + Alternatively you can pass the DSN via a _public_ environment variable like + `NEXT_PUBLIC_SENTRY_DSN`. + + +### Register Sentry Server-Side SDK Initialization While the client initialization code will be injected into your application's client bundle by `withSentryConfig` which we set up earlier, the configuration for the server and edge runtime needs to be imported from a [Next.js Instrumentation file](https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation). @@ -175,12 +229,11 @@ export async function register() { } ``` - Make sure that the `import` statements point to your newly created `sentry.server.config.(js|ts)` and `sentry.edge.config.(js|ts)` files. -## Report React Component Render Errors +## 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 respectively. +To capture React render errors you need to add Error components for the App Router. ### React Render Errors in App Router @@ -239,54 +292,7 @@ export default function GlobalError({ error }) { } ``` -Note that if you create [Next.js error.js files](https://nextjs.org/docs/app/building-your-application/routing/error-handling), these files will take precedence over the `global-error.js` file. -This means, that if you want to report errors that are caught by `error.js` files, you need to manually capture them: - -```tsx {filename:error.tsx} -"use client"; - -import { useEffect } from "react"; -import * as Sentry from "@sentry/nextjs"; - -export default function ErrorPage({ - error, -}: { - error: Error & { digest?: string }; -}) { - useEffect(() => { - // Log the error to Sentry - Sentry.captureException(error); - }, [error]); - - return ( -
-

Something went wrong!

-
- ); -} -``` - -```jsx {filename:error.jsx} -"use client"; - -import { useEffect } from "react"; -import * as Sentry from "@sentry/nextjs"; - -export default function ErrorPage({ error }) { - useEffect(() => { - // Log the error to Sentry - Sentry.captureException(error); - }, [error]); - - return ( -
-

Something went wrong!

-
- ); -} -``` - -#### Errors from Nested React Server Components +### Errors from Nested React Server Components _Requires `@sentry/nextjs` version `8.28.0` or higher and Next.js 15._ @@ -307,386 +313,200 @@ import * as Sentry from "@sentry/nextjs"; export const onRequestError = Sentry.captureRequestError; ``` -If you need additional logic within the `onRequestError` hook, call `captureRequestError` with all arguments passed to `onRequestError`: - -```TypeScript {filename:instrumentation.ts} -import * as Sentry from "@sentry/nextjs"; -import type { Instrumentation } from "next"; - -export const onRequestError: Instrumentation.onRequestError = (...args) => { - Sentry.captureRequestError(...args); - - // ... additional logic here -}; -``` - -```JavaScript {filename:instrumentation.js} -import * as Sentry from "@sentry/nextjs"; +## Step 4: Add readable Stack Traces With Source Maps (optional) -export const onRequestError = (...args) => { - Sentry.captureRequestError(...args); - - // ... additional logic here -}; -``` +By default, `withSentryConfig` will generate and upload source maps to Sentry automatically, so that errors have readable stack traces. +However, this only works if you provide an auth token in `withSentryConfig`. -### React Render Errors in Pages Router - -Create a [Custom Next.js Error Page](https://nextjs.org/docs/pages/building-your-application/routing/custom-error) and call `captureUnderscoreErrorException` in your Error Page's `getInitialProps` method: - -```TypeScript {filename:_error.tsx} -import * as Sentry from "@sentry/nextjs"; -import type { NextPage } from "next"; -import type { ErrorProps } from "next/error"; -import Error from "next/error"; - -const CustomErrorComponent: NextPage = (props) => { - return ; -}; - -CustomErrorComponent.getInitialProps = async (contextData) => { - // In case this is running in a serverless function, await this in order to give Sentry - // time to send the error before the lambda exits - await Sentry.captureUnderscoreErrorException(contextData); - - // This will contain the status code of the response - return Error.getInitialProps(contextData); -}; - -export default CustomErrorComponent; -``` - -```JavaScript {filename:_error.jsx} -import * as Sentry from "@sentry/nextjs"; -import Error from "next/error"; - -const CustomErrorComponent = (props) => { - return ; -}; - -CustomErrorComponent.getInitialProps = async (contextData) => { - // In case this is running in a serverless function, await this in order to give Sentry - // time to send the error before the lambda exits - await Sentry.captureUnderscoreErrorException(contextData); - - // This will contain the status code of the response - return Error.getInitialProps(contextData); -}; - -export default CustomErrorComponent; -``` - -## Instrument Next.js Server Actions - -_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: headers(), // Optionally pass in headers - recordResponse: true, // Optionally record the server action response - }, - async () => { - // ... Your Server Action code - - return { name: "John Doe" }; - } - ); - } - - return ( -
- - -
- ); -} -``` - -## Configure Source Maps - -By default, `withSentryConfig` will add a custom Webpack plugin to your configuration that runs for both server and client builds. -This means that when you run a production build (`next build`), sourcemaps will be generated and uploaded to Sentry, so that you get readable stack traces in your Sentry issues. - -For the SDK to be able to upload source maps to Sentry, you need to provide an auth token. -You can pass an auth token directly via the `authToken` option: +Update `withSentryConfig` in your `next.config.js` or `next.config.mjs` file with the following additions: ```javascript {tabTitle:ESM} {filename:next.config.mjs} export default withSentryConfig(nextConfig, { - // Specify the organization and project to upload source maps to - org: "___ORG_SLUG___", - project: "___PROJECT_SLUG___", - // Pass the auth token authToken: process.env.SENTRY_AUTH_TOKEN, + // Hides source maps from generated client bundles + hideSourceMaps: true, + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, }); ``` ```javascript {tabTitle:CJS} {filename:next.config.js} module.exports = withSentryConfig(nextConfig, { - // Specify the organization and project to upload source maps to - org: "___ORG_SLUG___", - project: "___PROJECT_SLUG___", - // Pass the auth token authToken: process.env.SENTRY_AUTH_TOKEN, + // Hides source maps from generated client bundles + hideSourceMaps: true, + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, }); ``` -Alternatively, you can set the `SENTRY_AUTH_TOKEN` environment variable: - - - -Do not commit your auth token to version control. - - +Alternatively, you can set the `SENTRY_AUTH_TOKEN` environment variable in your `.env` file: ```sh {filename:.env} SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ ``` -### Disable Source Maps + -You can disable the custom sourcemap plugin as follows: +Make sure to keep your auth token secret and don't commit it to version control. -```javascript {tabTitle:ESM} {filename:next.config.mjs} -export default withSentryConfig(nextConfig, { - sourcemaps: { - disable: true, - }, -}); -``` - -```javascript {tabTitle:CJS} {filename:next.config.js} -module.exports = withSentryConfig(nextConfig, { - sourcemaps: { - disable: true, - }, -}); -``` + -### Use `hidden-source-map` +## Step 5: Instrumentation of Vercel Cron Jobs (optional) -Depending on your deployment setup, adding `sentry/nextjs` to your app may cause your source code to be visible in browser devtools when it wasn't before. (This happens because of the default behavior of [webpack's `source-map` built-in `devtool`](https://webpack.js.org/configuration/devtool/).) To prevent this, you can use `hidden-source-map` rather than `source-map`, which will prevent your built files from containing a `sourceMappingURL` comment, thus making sourcemaps invisible to the browser. To use `hidden-source-map`, add a `sentry` object to `nextConfig` above, and set the `hideSourceMaps` option to `true`: +If you have configured [Vercel Cron Jobs](https://vercel.com/docs/cron-jobs) you can set the `automaticVercelMonitors` option to automatically create [Cron Monitors](/product/crons/) in Sentry. ```javascript {tabTitle:ESM} {filename:next.config.mjs} export default withSentryConfig(nextConfig, { - hideSourceMaps: true, + automaticVercelMonitors: true, }); ``` ```javascript {tabTitle:CJS} {filename:next.config.js} module.exports = withSentryConfig(nextConfig, { - hideSourceMaps: true, + automaticVercelMonitors: true, }); ``` -### Widen the Upload Scope - -If you find that there are some frames in your client-side stack traces that aren't getting source-mapped even when most others are, the issue might be that those frames are from files in `static/chunks/` rather than `static/chunks/pages/`. By default, such files aren't uploaded because the majority of the files in `static/chunks/` only contain Next.js or third-party code. - -To upload all of the files and source maps, including ones from third-party packages, set the `widenClientFileUpload` option to `true`: + -```javascript {tabTitle:ESM} {filename:next.config.mjs} -export default withSentryConfig(nextConfig, { - widenClientFileUpload: true, -}); -``` +Automatic instrumentation of Vercel cron jobs currently only works for the Pages Router. App Router route handlers are not yet supported. -```javascript {tabTitle:CJS} {filename:next.config.js} -module.exports = withSentryConfig(nextConfig, { - widenClientFileUpload: true, -}); -``` + -## Configure Tunneling to avoid Ad-Blockers +## Step 6: Capture React Component Names (optional) -You might notice that Sentry events are sometimes blocked by ad blockers. -Ad blockers can be circumvented by using **tunneling**. +You can capture the names of React components in your application, so that you can, for example, see the name of a component that a user clicked on in different Sentry features, like Session Replay and Performance page. -The Sentry Next.js SDK provides an easy way to set up tunneling for your application. -Use the `tunnelRoute` option to provide the SDK a route to use to tunnel events to Sentry: +Update `withSentryConfig` in your `next.config.js` or `next.config.mjs` with the following addition to capture component names: ```javascript {tabTitle:ESM} {filename:next.config.mjs} export default withSentryConfig(nextConfig, { - tunnelRoute: "/monitoring-tunnel", + reactComponentAnnotation: { + enabled: true, + }, }); ``` ```javascript {tabTitle:CJS} {filename:next.config.js} module.exports = withSentryConfig(nextConfig, { - tunnelRoute: "/monitoring-tunnel", + reactComponentAnnotation: { + enabled: true, + }, }); ``` -Setting this option will add an API endpoint to your application that is used to forward Sentry events to the Sentry servers. +## Step 7: Verify -Complications when using tunnelRoute with Next.js Middleware}> + -If the route configured with `tunnelRoute` is intercepted by your Next.js middleware, the client-side events recording will fail. You can exclude the tunnel route by adding a negative matcher to your middleware like this: `(?!monitoring-tunnel)` - - +The Sentry SDK doesn't fully support `next dev --turbo` as Turbopack is still under development. This means that the Sentry SDK will not capture any data from your frontend. Other than that, your dev server should be fully operational. -Please note that this option will tunnel Sentry events through your Next.js application so you might experience increased server usage. +Check the latest information on [Sentry's support for Turbopack on GitHub](https://github.com/getsentry/sentry-javascript/issues/8105). -The `tunnelRoute` option does currently not work with self-hosted Sentry instances. + -Learn more about tunneling in the troubleshooting section. +Let's test your setup and confirm that Sentry is working properly and sending data to your Sentry project. -## Configure Server-side Auto-instrumentation +### Issues -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. +To test if Sentry captures errors and creates issues for them in your Sentry project, add a test button to one of your existing pages or create a new one: -### 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, -}); +```javascript + ``` -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 + + Open the page with your test button in it in your browser. For most Next.js + applications, this will be at localhost. Clicking the button triggers a + frontend error. + -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. + +### Tracing -For API routes, use the `wrapApiHandlerWithSentry` function: +To see whether Sentry tracing is working, create a test route that throws an error: -```javascript {filename:pages/api/*} -import { wrapApiHandlerWithSentry } from "@sentry/nextjs"; - -const handler = (req, res) => { - res.status(200).json({ name: "John Doe" }); -}; +```javascript +import { NextResponse } from "next/server"; +export const dynamic = "force-dynamic"; -export default wrapApiHandlerWithSentry(handler, "/api/myRoute"); +// A faulty API route to test Sentry's error monitoring +export function GET() { + throw new Error("Sentry Example API Route Error"); + return NextResponse.json({ data: "Testing Sentry Error..." }); +} ``` -```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" }); -}; +Next, update the `onClick` event in your button to call the API route and throw an error if the API response is not `ok`: -export default wrapApiHandlerWithSentry(handler, "/api/myRoute"); +```javascript +onClick={async () => { + await Sentry.startSpan({ + name: 'Example Frontend Span', + op: 'test' + }, async () => { + const res = await fetch("/api/sentry-example-api"); + if (!res.ok) { + throw new Error("Sentry Example Frontend Error"); + } + }); + } ``` -For data fetching methods, use the following functions: +Open the page with your test button in it in your browser. For most Next.js applications, this will be at localhost. +Clicking the button triggers two errors: -- `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) +- a frontend error +- an error within the API route -### Opt Out of Auto-instrumentation on Specific Routes +Sentry captures both of these errors for you. Additionally, the button click starts a performance trace to measure the time it takes for the API request to complete. -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\/?/, - ], -}); -``` +### View Captured Data in Sentry -```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 +Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). -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, -}); -``` +Errors triggered from within your browser's developer tools (i.e., the browser console) are sandboxed, so they will not trigger Sentry's error monitoring. -### Instrumentation of Vercel Cron Jobs + -You can set the `automaticVercelMonitors` option to automatically create [Cron Monitors](/product/crons/) in Sentry if you have configured [Vercel Cron Jobs](https://vercel.com/docs/cron-jobs). + - +1. Open the [**Issues**](https://sentry.io/orgredirect/organizations/:orgslug/issues) page and select an error from the issues list to view the full details and context of this error. For an interactive UI walkthrough, click [here](/product/sentry-basics/integrate-frontend/generate-first-error/#ui-walkthrough). +2. Open the [**Traces**](https://sentry.io/orgredirect/organizations/:orgslug/traces) page and select a trace to reveal more information about each span, its duration, and any errors. For an interactive UI walkthrough, click [here](/product/sentry-basics/distributed-tracing/generate-first-error/#ui-walkthrough). +3. Open the [**Replays**](https://sentry.io/orgredirect/organizations/:orgslug/replays) page and select an entry from the list to get a detailed view where you can replay the interaction and get more information to help you troubleshoot. -Automatic instrumentation of Vercel cron jobs currently only works for the Pages Router. App Router route handlers are not yet supported. + - - -```javascript {tabTitle:ESM} {filename:next.config.mjs} -export default withSentryConfig(nextConfig, { - automaticVercelMonitors: true, -}); -``` - -```javascript {tabTitle:CJS} {filename:next.config.js} -module.exports = withSentryConfig(nextConfig, { - automaticVercelMonitors: true, -}); -``` +## Next Steps -### Opt Out of Sentry SDK bundling in Client- or Server-Side +At this point, you should have integrated Sentry into your Next.js application and should already be sending error and performance data to your Sentry project. -If you want the Sentry SDK to be available in your server-side & not in client-side, you can simply delete `sentry.client.config.js`. 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`. +Now's a good time to customize your setup and look into more advanced topics. +Our next recommended steps for you are: -## Disable the Sentry SDK Debug Logger to Save Bundle Size +- Instrument Next.js server actions +- Add error components for the Pages Router +- Learn how to [manually capture errors](/platforms/javascript/guides/nextjs/usage/) +- Continue to [customize your configuration](/platforms/javascript/guides/nextjs/configuration/) +- Learn more about our [Vercel integration](/organization/integrations/deployment/vercel/) -Set the `disableLogger` option to `true` to strip the Sentry SDK debug logger out of your client bundles, saving bundle size. -Please note that this will effectively override and disable the `debug` option in your `Sentry.init()` calls. + -```javascript {tabTitle:ESM} {filename:next.config.mjs} -export default withSentryConfig(nextConfig, { - disableLogger: true, -}); -``` +- If you encountered issues with our installation wizard, try [setting up Sentry manually](/platforms/javascript/guides/nextjs/manual-setup/) +- [Get support](https://sentry.zendesk.com/hc/en-us/) -```javascript {tabTitle:CJS} {filename:next.config.js} -module.exports = withSentryConfig(nextConfig, { - disableLogger: true, -}); -``` + From ce22d8c2a5ab7626c95e6aa1d93eb78e41a05128 Mon Sep 17 00:00:00 2001 From: Sarah Mischinger Date: Tue, 11 Feb 2025 11:08:19 +0100 Subject: [PATCH 02/10] fix title typo --- docs/platforms/javascript/guides/nextjs/manual-setup.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx index 5a2fceebdbb18..1bb42c7ace83d 100644 --- a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx +++ b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx @@ -1,5 +1,5 @@ --- -title: "Quickstart: Manual Setup" +title: "Quick Start: Manual Setup" sidebar_order: 1 description: "Learn how to manually set up and configure Sentry in your Next.js application, capture your first errors, and view them in Sentry." --- From 97f6bbba94556461a6a361437720ec93c1814772 Mon Sep 17 00:00:00 2001 From: Sarah Mischinger Date: Wed, 12 Feb 2025 09:31:19 +0100 Subject: [PATCH 03/10] feedback updates --- .../javascript/guides/nextjs/manual-setup.mdx | 62 ++++++++++--------- 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx index 1bb42c7ace83d..3c0e09bf72a2b 100644 --- a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx +++ b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx @@ -1,5 +1,5 @@ --- -title: "Quick Start: Manual Setup" +title: "Manual Setup" sidebar_order: 1 description: "Learn how to manually set up and configure Sentry in your Next.js application, capture your first errors, and view them in Sentry." --- @@ -7,28 +7,13 @@ description: "Learn how to manually set up and configure Sentry in your Next.js ## Prerequisites - A Sentry [account](https://sentry.io/signup/) and [project](https://docs.sentry.io/product/projects/) -- Be logged in to your Sentry account to have your project's data pre-filled (recommended) - Your application up and running ## Step 1: Install -Run the following command for your preferred package manager to add the Sentry SDK to your application: - -```bash {tabTitle:npm} -npm install @sentry/nextjs --save -``` - -```bash {tabTitle:yarn} -yarn add @sentry/nextjs -``` - -```bash {tabTitle:pnpm} -pnpm add @sentry/nextjs -``` - ### Choose Your Sentry Features -Select the features you want to set up in your application, in addition to error monitoring, using the checkboxes below. This guide will then adjust its content to provide you with the necessary information. +Select the features you want to set up using the checkboxes below. This guide will then adjust its content to provide you with the necessary information. @@ -51,6 +36,22 @@ You can add or remove features at any time, but setting them up now will save yo options={["error-monitoring", "performance", "session-replay"]} /> +### Install the Sentry SDK + +Run the following command for your preferred package manager to add the Sentry SDK to your application: + +```bash {tabTitle:npm} +npm install @sentry/nextjs --save +``` + +```bash {tabTitle:yarn} +yarn add @sentry/nextjs +``` + +```bash {tabTitle:pnpm} +pnpm add @sentry/nextjs +``` + ## Step 2: Configure ### Apply Instrumentation to Your App @@ -292,7 +293,12 @@ export default function GlobalError({ error }) { } ``` -### Errors from Nested React Server Components + + You can also add Error components for the Pages Router, which you can learn + more about here (LINK!). + + +### Errors From Nested React Server Components _Requires `@sentry/nextjs` version `8.28.0` or higher and Next.js 15._ @@ -313,7 +319,7 @@ import * as Sentry from "@sentry/nextjs"; export const onRequestError = Sentry.captureRequestError; ``` -## Step 4: Add readable Stack Traces With Source Maps (optional) +## Step 4: Add Readable Stack Traces With Source Maps (Optional) By default, `withSentryConfig` will generate and upload source maps to Sentry automatically, so that errors have readable stack traces. However, this only works if you provide an auth token in `withSentryConfig`. @@ -354,7 +360,7 @@ Make sure to keep your auth token secret and don't commit it to version control. -## Step 5: Instrumentation of Vercel Cron Jobs (optional) +## Step 5: Instrumentation of Vercel Cron Jobs (Optional) If you have configured [Vercel Cron Jobs](https://vercel.com/docs/cron-jobs) you can set the `automaticVercelMonitors` option to automatically create [Cron Monitors](/product/crons/) in Sentry. @@ -376,11 +382,11 @@ Automatic instrumentation of Vercel cron jobs currently only works for the Pages -## Step 6: Capture React Component Names (optional) +## Step 6: Capture React Component Names (Optional) -You can capture the names of React components in your application, so that you can, for example, see the name of a component that a user clicked on in different Sentry features, like Session Replay and Performance page. +You can capture the names of React components in your application, so that you can, for example, see the name of a component that a user clicked on in different Sentry features, like Session Replay and the Performance page. -Update `withSentryConfig` in your `next.config.js` or `next.config.mjs` with the following addition to capture component names: +Update `withSentryConfig` in your `next.config.js` or `next.config.mjs` with the following option to capture component names: ```javascript {tabTitle:ESM} {filename:next.config.mjs} export default withSentryConfig(nextConfig, { @@ -426,7 +432,7 @@ To test if Sentry captures errors and creates issues for them in your Sentry pro ``` - Open the page with your test button in it in your browser. For most Next.js + Open the page with your test button in a browser. For most Next.js applications, this will be at localhost. Clicking the button triggers a frontend error. @@ -463,7 +469,7 @@ onClick={async () => { } ``` -Open the page with your test button in it in your browser. For most Next.js applications, this will be at localhost. +Open the page with your test button in a browser. For most Next.js applications, this will be at localhost. Clicking the button triggers two errors: - a frontend error @@ -479,7 +485,7 @@ Now, head over to your project on [Sentry.io](https://sentry.io) to view the col -Errors triggered from within your browser's developer tools (i.e., the browser console) are sandboxed, so they will not trigger Sentry's error monitoring. +Errors triggered from within your browser's developer tools (like the browser console) are sandboxed, so they will not trigger Sentry's error monitoring. @@ -493,13 +499,13 @@ Errors triggered from within your browser's developer tools (i.e., the browser c ## Next Steps -At this point, you should have integrated Sentry into your Next.js application and should already be sending error and performance data to your Sentry project. +At this point, you should have integrated Sentry into your Next.js application and should already be sending data to your Sentry project. Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are: - Instrument Next.js server actions -- Add error components for the Pages Router +- Configure [server-side auto-instrumentation](/platforms/javascript/guides/nextjs/configuration/build/#nextjs-specific-options) - Learn how to [manually capture errors](/platforms/javascript/guides/nextjs/usage/) - Continue to [customize your configuration](/platforms/javascript/guides/nextjs/configuration/) - Learn more about our [Vercel integration](/organization/integrations/deployment/vercel/) From be7249146128610224a0f97582c5854fdc65ea4b Mon Sep 17 00:00:00 2001 From: Sarah Mischinger Date: Thu, 13 Feb 2025 09:10:56 +0100 Subject: [PATCH 04/10] pr feedback --- .../javascript/guides/nextjs/manual-setup.mdx | 147 ++++++++++++------ 1 file changed, 102 insertions(+), 45 deletions(-) diff --git a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx index 3c0e09bf72a2b..f17a5e1c72a88 100644 --- a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx +++ b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx @@ -4,6 +4,12 @@ sidebar_order: 1 description: "Learn how to manually set up and configure Sentry in your Next.js application, capture your first errors, and view them in Sentry." --- + + For the fastest setup, we recommend using our [wizard + installer](/platforms/javascript/guides/nextjs/#install) to automatically + configure Sentry in your application. + + ## Prerequisites - A Sentry [account](https://sentry.io/signup/) and [project](https://docs.sentry.io/product/projects/) @@ -73,14 +79,9 @@ module.exports = withSentryConfig(nextConfig, { project: "___PROJECT_SLUG___", // Only print logs for uploading source maps in CI - // Set to `false` to surpress logs + // Set to `true` to suppress logs silent: !process.env.CI, - // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. - // This can increase your server load as well as your hosting bill. - // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client-side errors will fail. - tunnelRoute: "/monitoring", - // Automatically tree-shake Sentry logger statements to reduce bundle size disableLogger: true, }); @@ -99,26 +100,14 @@ export default withSentryConfig(nextConfig, { project: "___PROJECT_SLUG___", // Only print logs for uploading source maps in CI - // Set to `false` to surpress logs + // Set to `true` to suppress logs silent: !process.env.CI, - // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. - // This can increase your server load as well as your hosting bill. - // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client-side errors will fail. - tunnelRoute: "/monitoring", - // Automatically tree-shake Sentry logger statements to reduce bundle size disableLogger: true, }); ``` - - You might notice that ad blockers sometimes block Sentry events, which you can - circumvent using tunneling. Setting the `tunnelRoute` option will add an API - endpoint to your application that is used to forward Sentry events to the - Sentry servers. - - ### Initialize Sentry Client-Side and Server-Side SDKs Create three files in the root directory of your Next.js application: `sentry.client.config.js`, `sentry.server.config.js` and `sentry.edge.config.js`. In these files, add your initialization code for the client-side SDK and server-side SDK, respectively. We've included some examples below. @@ -128,7 +117,7 @@ Create three files in the root directory of your Next.js application: `sentry.cl places (browser, server, edge), so copy them carefully! -```javascript {tabTitle:Client} {filename:sentry.client.config.(js|ts)} {"onboardingOptions": {"performance": "8-13", "session-replay": "5-6, 15-20"}} +```javascript {tabTitle:Client} {filename:sentry.client.config.(js|ts)} {"onboardingOptions": {"performance": "7-13", "session-replay": "5-6, 14-20"}} import * as Sentry from "@sentry/nextjs"; Sentry.init({ @@ -158,7 +147,7 @@ Sentry.init({ }); ``` -```javascript {tabTitle:Server} {filename:sentry.server.config.(js|ts)} {"onboardingOptions": {"performance": "6-11"}} +```javascript {tabTitle:Server} {filename:sentry.server.config.(js|ts)} {"onboardingOptions": {"performance": "5-11"}} import * as Sentry from "@sentry/nextjs"; Sentry.init({ @@ -179,7 +168,7 @@ Sentry.init({ }); ``` -```javascript {tabTitle:Edge} {filename:sentry.edge.config.(js|ts)} {"onboardingOptions": {"performance": "6-11"}} +```javascript {tabTitle:Edge} {filename:sentry.edge.config.(js|ts)} {"onboardingOptions": {"performance": "5-11"}} import * as Sentry from "@sentry/nextjs"; Sentry.init({ @@ -234,7 +223,7 @@ Make sure that the `import` statements point to your newly created `sentry.serve ## Step 3: Capture React Render Errors -To capture React render errors you need to add Error components for the App Router. +To capture React render errors you need to add Error components for the App Router and the Pages Router respectively. ### React Render Errors in App Router @@ -293,11 +282,6 @@ export default function GlobalError({ error }) { } ``` - - You can also add Error components for the Pages Router, which you can learn - more about here (LINK!). - - ### Errors From Nested React Server Components _Requires `@sentry/nextjs` version `8.28.0` or higher and Next.js 15._ @@ -319,6 +303,54 @@ import * as Sentry from "@sentry/nextjs"; export const onRequestError = Sentry.captureRequestError; ``` +### React Render Errors in Pages Router + +Create a [Custom Next.js Error Page](https://nextjs.org/docs/pages/building-your-application/routing/custom-error) and call `captureUnderscoreErrorException` in your Error Page's `getInitialProps` method: + +```tsx {filename:_error.tsx} +import * as Sentry from "@sentry/nextjs"; +import type { NextPage } from "next"; +import type { ErrorProps } from "next/error"; +import Error from "next/error"; + +const CustomErrorComponent: NextPage = (props) => { + return ; +}; + +CustomErrorComponent.getInitialProps = async (contextData) => { + // In case this is running in a serverless function, await this in order to give Sentry + // time to send the error before the lambda exits + await Sentry.captureUnderscoreErrorException(contextData); + + // This will contain the status code of the response + return Error.getInitialProps(contextData); +}; + +export default CustomErrorComponent; +``` + +```jsx {filename:_error.jsx} +import * as Sentry from "@sentry/nextjs"; +import type { NextPage } from "next"; +import type { ErrorProps } from "next/error"; +import Error from "next/error"; + +const CustomErrorComponent: NextPage = (props) => { + return ; +}; + +CustomErrorComponent.getInitialProps = async (contextData) => { + // In case this is running in a serverless function, await this in order to give Sentry + // time to send the error before the lambda exits + await Sentry.captureUnderscoreErrorException(contextData); + + // This will contain the status code of the response + return Error.getInitialProps(contextData); +}; + +export default CustomErrorComponent; +``` + ## Step 4: Add Readable Stack Traces With Source Maps (Optional) By default, `withSentryConfig` will generate and upload source maps to Sentry automatically, so that errors have readable stack traces. @@ -330,8 +362,6 @@ Update `withSentryConfig` in your `next.config.js` or `next.config.mjs` file wit export default withSentryConfig(nextConfig, { // Pass the auth token authToken: process.env.SENTRY_AUTH_TOKEN, - // Hides source maps from generated client bundles - hideSourceMaps: true, // Upload a larger set of source maps for prettier stack traces (increases build time) widenClientFileUpload: true, }); @@ -341,8 +371,6 @@ export default withSentryConfig(nextConfig, { module.exports = withSentryConfig(nextConfig, { // Pass the auth token authToken: process.env.SENTRY_AUTH_TOKEN, - // Hides source maps from generated client bundles - hideSourceMaps: true, // Upload a larger set of source maps for prettier stack traces (increases build time) widenClientFileUpload: true, }); @@ -360,7 +388,31 @@ Make sure to keep your auth token secret and don't commit it to version control. -## Step 5: Instrumentation of Vercel Cron Jobs (Optional) +## Step 5: Avoid Ad Blockers With Tunneling (Optional) + +You might notice that ad blockers sometimes block Sentry events, which you can circumvent using tunneling. Setting the `tunnelRoute` option will add an API endpoint to your application that is used to forward Sentry events to the Sentry servers. + +Update `withSentryConfig` in your `next.config.js` or `next.config.mjs` file with the following option: + +```javascript {tabTitle:ESM} {filename:next.config.mjs} +export default withSentryConfig(nextConfig, { + // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client-side errors will fail. + tunnelRoute: "/monitoring", +}); +``` + +```javascript {tabTitle:CJS} {filename:next.config.js} +module.exports = withSentryConfig(nextConfig, { + // Route browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. + // This can increase your server load as well as your hosting bill. + // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client-side errors will fail. + tunnelRoute: "/monitoring", +}); +``` + +## Step 6: Instrument Vercel Cron Jobs (Optional) If you have configured [Vercel Cron Jobs](https://vercel.com/docs/cron-jobs) you can set the `automaticVercelMonitors` option to automatically create [Cron Monitors](/product/crons/) in Sentry. @@ -382,7 +434,7 @@ Automatic instrumentation of Vercel cron jobs currently only works for the Pages -## Step 6: Capture React Component Names (Optional) +## Step 7: Capture React Component Names (Optional) You can capture the names of React components in your application, so that you can, for example, see the name of a component that a user clicked on in different Sentry features, like Session Replay and the Performance page. @@ -404,7 +456,7 @@ module.exports = withSentryConfig(nextConfig, { }); ``` -## Step 7: Verify +## Step 8: Verify @@ -420,7 +472,7 @@ Let's test your setup and confirm that Sentry is working properly and sending da To test if Sentry captures errors and creates issues for them in your Sentry project, add a test button to one of your existing pages or create a new one: -```javascript +```jsx ; ``` Open the page with your test button in a browser. For most Next.js applications, this will be at localhost. @@ -483,12 +546,6 @@ Sentry captures both of these errors for you. Additionally, the button click sta Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). - - -Errors triggered from within your browser's developer tools (like the browser console) are sandboxed, so they will not trigger Sentry's error monitoring. - - - 1. Open the [**Issues**](https://sentry.io/orgredirect/organizations/:orgslug/issues) page and select an error from the issues list to view the full details and context of this error. For an interactive UI walkthrough, click [here](/product/sentry-basics/integrate-frontend/generate-first-error/#ui-walkthrough). @@ -512,7 +569,7 @@ Our next recommended steps for you are: -- If you encountered issues with our installation wizard, try [setting up Sentry manually](/platforms/javascript/guides/nextjs/manual-setup/) +- If you encountered issues with setting up Sentry manually, [try our installation wizard](/platforms/javascript/guides/nextjs/) - [Get support](https://sentry.zendesk.com/hc/en-us/) From 9c1cf0d51b715de4b6837e85114cdcb2fef4b6f8 Mon Sep 17 00:00:00 2001 From: Sarah Mischinger Date: Thu, 13 Feb 2025 09:45:57 +0100 Subject: [PATCH 05/10] add tunneling alert --- .../javascript/guides/nextjs/manual-setup.mdx | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx index f17a5e1c72a88..d7b449fb38f2d 100644 --- a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx +++ b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx @@ -6,8 +6,8 @@ description: "Learn how to manually set up and configure Sentry in your Next.js For the fastest setup, we recommend using our [wizard - installer](/platforms/javascript/guides/nextjs/#install) to automatically - configure Sentry in your application. + installer](/platforms/javascript/guides/nextjs) to automatically configure + Sentry in your application. ## Prerequisites @@ -412,6 +412,16 @@ module.exports = withSentryConfig(nextConfig, { }); ``` + + If the route configured with `tunnelRoute` is intercepted by your Next.js + middleware, the client-side events recording will fail. You can exclude the + tunnel route by adding a negative matcher to your middleware like this: + `(?!monitoring-tunnel)`. + + ## Step 6: Instrument Vercel Cron Jobs (Optional) If you have configured [Vercel Cron Jobs](https://vercel.com/docs/cron-jobs) you can set the `automaticVercelMonitors` option to automatically create [Cron Monitors](/product/crons/) in Sentry. From 43b7a8d60483edc2f5363da18cc3e8580f340de1 Mon Sep 17 00:00:00 2001 From: Sarah Mischinger Date: Thu, 13 Feb 2025 10:23:51 +0100 Subject: [PATCH 06/10] pr feedback --- .../javascript/guides/nextjs/manual-setup.mdx | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx index d7b449fb38f2d..4b5cf62843982 100644 --- a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx +++ b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx @@ -303,6 +303,29 @@ import * as Sentry from "@sentry/nextjs"; export const onRequestError = Sentry.captureRequestError; ``` +If you need additional logic within the `onRequestError` hook, call `captureRequestError` with all arguments passed to `onRequestError`: + +```TypeScript {filename:instrumentation.ts} +import * as Sentry from "@sentry/nextjs"; +import type { Instrumentation } from "next"; + +export const onRequestError: Instrumentation.onRequestError = (...args) => { + Sentry.captureRequestError(...args); + + // ... additional logic here +}; +``` + +```JavaScript {filename:instrumentation.js} +import * as Sentry from "@sentry/nextjs"; + +export const onRequestError = (...args) => { + Sentry.captureRequestError(...args); + + // ... additional logic here +}; +``` + ### React Render Errors in Pages Router Create a [Custom Next.js Error Page](https://nextjs.org/docs/pages/building-your-application/routing/custom-error) and call `captureUnderscoreErrorException` in your Error Page's `getInitialProps` method: @@ -360,6 +383,9 @@ Update `withSentryConfig` in your `next.config.js` or `next.config.mjs` file wit ```javascript {tabTitle:ESM} {filename:next.config.mjs} export default withSentryConfig(nextConfig, { + org: "___ORG_SLUG___", + project: "___PROJECT_SLUG___", + // Pass the auth token authToken: process.env.SENTRY_AUTH_TOKEN, // Upload a larger set of source maps for prettier stack traces (increases build time) @@ -369,6 +395,9 @@ export default withSentryConfig(nextConfig, { ```javascript {tabTitle:CJS} {filename:next.config.js} module.exports = withSentryConfig(nextConfig, { + org: "___ORG_SLUG___", + project: "___PROJECT_SLUG___", + // Pass the auth token authToken: process.env.SENTRY_AUTH_TOKEN, // Upload a larger set of source maps for prettier stack traces (increases build time) @@ -577,7 +606,7 @@ Our next recommended steps for you are: - Continue to [customize your configuration](/platforms/javascript/guides/nextjs/configuration/) - Learn more about our [Vercel integration](/organization/integrations/deployment/vercel/) - + - If you encountered issues with setting up Sentry manually, [try our installation wizard](/platforms/javascript/guides/nextjs/) - [Get support](https://sentry.zendesk.com/hc/en-us/) From 64d307b4c5bd9f2c7ef59f80f7c2f2af470f3e76 Mon Sep 17 00:00:00 2001 From: Sarah Mischinger Date: Tue, 18 Feb 2025 14:49:19 +0100 Subject: [PATCH 07/10] shorten and edit guide content --- .../javascript/guides/nextjs/manual-setup.mdx | 131 ++++++++---------- 1 file changed, 58 insertions(+), 73 deletions(-) diff --git a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx index 4b5cf62843982..7f6002b4d7c0f 100644 --- a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx +++ b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx @@ -1,13 +1,12 @@ --- title: "Manual Setup" sidebar_order: 1 -description: "Learn how to manually set up and configure Sentry in your Next.js application, capture your first errors, and view them in Sentry." +description: "Learn how to manually set up Sentry in your Next.js app and capture your first errors." --- - For the fastest setup, we recommend using our [wizard - installer](/platforms/javascript/guides/nextjs) to automatically configure - Sentry in your application. + For the fastest setup, we recommend using the [wizard + installer](/platforms/javascript/guides/nextjs). ## Prerequisites @@ -17,9 +16,11 @@ description: "Learn how to manually set up and configure Sentry in your Next.js ## Step 1: Install -### Choose Your Sentry Features +Choose the features you want to configure, and this guide will show you how: -Select the features you want to set up using the checkboxes below. This guide will then adjust its content to provide you with the necessary information. + @@ -36,15 +37,9 @@ Select the features you want to set up using the checkboxes below. This guide wi -You can add or remove features at any time, but setting them up now will save you the effort of configuring them manually later. - - - ### Install the Sentry SDK -Run the following command for your preferred package manager to add the Sentry SDK to your application: +Run the command for your preferred package manager to add the Sentry SDK to your application: ```bash {tabTitle:npm} npm install @sentry/nextjs --save @@ -62,9 +57,7 @@ pnpm add @sentry/nextjs ### Apply Instrumentation to Your App -To apply instrumentation to your application, use `withSentryConfig` to extend your app's default Next.js options. - -Update your `next.config.js` or `next.config.mjs` file with the following: +Extend your app's default Next.js options by adding `withSentryConfig` into your `next.config.(js|mjs)` file: ```JavaScript {tabTitle:CJS} {filename:next.config.js} const { withSentryConfig } = require("@sentry/nextjs"); @@ -110,11 +103,11 @@ export default withSentryConfig(nextConfig, { ### Initialize Sentry Client-Side and Server-Side SDKs -Create three files in the root directory of your Next.js application: `sentry.client.config.js`, `sentry.server.config.js` and `sentry.edge.config.js`. In these files, add your initialization code for the client-side SDK and server-side SDK, respectively. We've included some examples below. +Create three files in your application's root directory: `sentry.client.config.(js|ts)`, `sentry.server.config.(js|ts)` and `sentry.edge.config.(js|ts)`. Add the following initialization code into each respective file: - There are slight differences between these files since they run in different - places (browser, server, edge), so copy them carefully! + These files run in different environments (browser, server, edge) and are + slightly different, so copy them carefully. ```javascript {tabTitle:Client} {filename:sentry.client.config.(js|ts)} {"onboardingOptions": {"performance": "7-13", "session-replay": "5-6, 14-20"}} @@ -190,22 +183,14 @@ Sentry.init({ ``` - We recommend you include your [Data Source - Name](/concepts/key-terms/dsn-explainer/) (DSN) directly in these three files. - Alternatively you can pass the DSN via a _public_ environment variable like + Include your [Data Source Name](/concepts/key-terms/dsn-explainer/) (DSN) + directly in these files, or use a _public_ environment variable like `NEXT_PUBLIC_SENTRY_DSN`. ### Register Sentry Server-Side SDK Initialization -While the client initialization code will be injected into your application's client bundle by `withSentryConfig` which we set up earlier, -the configuration for the server and edge runtime needs to be imported from a [Next.js Instrumentation file](https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation). - - -For Next.js versions `<15` enable the Next.js instrumentation hook by setting the [`experimental.instrumentationHook`](https://nextjs.org/docs/14/pages/api-reference/next-config-js/instrumentationHook) to `true` in your `next.config.js`. - - -Add a `instrumentation.ts` file to the root directory of your Next.js application (or inside the `src` folder if you're using one) and add the following content: +Create a [Next.js Instrumentation file](https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation) named `instrumentation.(js|ts)` in your project root or inside the `src` folder if you have one. Import your server and edge configurations, making sure that the imports point to your specific files: ```javascript {filename:instrumentation.(js|ts)} export async function register() { @@ -219,15 +204,19 @@ export async function register() { } ``` -Make sure that the `import` statements point to your newly created `sentry.server.config.(js|ts)` and `sentry.edge.config.(js|ts)` files. + + You need to enable the instrumentation hook by setting the + `experimental.instrumentationHook` to `true` in your `next.config.(js|mjs)` + file. + ## 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 respectively. +To capture React render errors, you need to add error components for the App Router and the Pages Router. -### React Render Errors in App Router +### App Router -Create a [Custom Next.js Global Error component](https://nextjs.org/docs/app/building-your-application/routing/error-handling) for the App router: +Create or update the `global-error.(tsx|jsx)` file to define a [custom Next.js GlobalError component](https://nextjs.org/docs/app/building-your-application/routing/error-handling): ```tsx {filename:global-error.tsx} "use client"; @@ -282,14 +271,13 @@ export default function GlobalError({ error }) { } ``` -### Errors From Nested React Server Components +### Nested React Server Component Errors -_Requires `@sentry/nextjs` version `8.28.0` or higher and Next.js 15._ - -To capture errors from nested React Server Components, use the `onRequestError` hook in `instrumentation.(js|ts)`. -[The `onRequestError` hook is a feature provided by Next.js](https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation#onrequesterror-optional), which allows reporting errors to Sentry. + + Requires `@sentry/nextjs` version `8.28.0` or higher and Next.js 15. + -To report errors using the `onRequestError` hook, pass all arguments to the `captureRequestError` function: +To capture errors from nested React Server Components, use the [`onRequestError`](https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation#onrequesterror-optional) hook in `instrumentation.(js|ts)` and pass all arguments to the `captureRequestError` function: ```TypeScript {filename:instrumentation.ts} import * as Sentry from "@sentry/nextjs"; @@ -303,7 +291,8 @@ import * as Sentry from "@sentry/nextjs"; export const onRequestError = Sentry.captureRequestError; ``` -If you need additional logic within the `onRequestError` hook, call `captureRequestError` with all arguments passed to `onRequestError`: + +You can call `captureRequestError` with all arguments passed to `onRequestError`: ```TypeScript {filename:instrumentation.ts} import * as Sentry from "@sentry/nextjs"; @@ -326,9 +315,11 @@ export const onRequestError = (...args) => { }; ``` -### React Render Errors in Pages Router + + +### Pages Router -Create a [Custom Next.js Error Page](https://nextjs.org/docs/pages/building-your-application/routing/custom-error) and call `captureUnderscoreErrorException` in your Error Page's `getInitialProps` method: +Create or update the `_error.(tsx|jsx)` file to define a [custom Next.js error page](https://nextjs.org/docs/pages/building-your-application/routing/custom-error) for the Pages Router like so: ```tsx {filename:_error.tsx} import * as Sentry from "@sentry/nextjs"; @@ -376,10 +367,9 @@ export default CustomErrorComponent; ## Step 4: Add Readable Stack Traces With Source Maps (Optional) -By default, `withSentryConfig` will generate and upload source maps to Sentry automatically, so that errors have readable stack traces. -However, this only works if you provide an auth token in `withSentryConfig`. +Sentry can automatically provide readable stack traces for errors using source maps, requiring a Sentry auth token. -Update `withSentryConfig` in your `next.config.js` or `next.config.mjs` file with the following additions: +Update your `next.config.(js|mjs)` file with the following options: ```javascript {tabTitle:ESM} {filename:next.config.mjs} export default withSentryConfig(nextConfig, { @@ -405,7 +395,7 @@ module.exports = withSentryConfig(nextConfig, { }); ``` -Alternatively, you can set the `SENTRY_AUTH_TOKEN` environment variable in your `.env` file: +Alternatively, set the `SENTRY_AUTH_TOKEN` environment variable in your `.env` file: ```sh {filename:.env} SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ @@ -413,15 +403,15 @@ SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ -Make sure to keep your auth token secret and don't commit it to version control. +Make sure to keep your auth token secret and out of version control. ## Step 5: Avoid Ad Blockers With Tunneling (Optional) -You might notice that ad blockers sometimes block Sentry events, which you can circumvent using tunneling. Setting the `tunnelRoute` option will add an API endpoint to your application that is used to forward Sentry events to the Sentry servers. +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. -Update `withSentryConfig` in your `next.config.js` or `next.config.mjs` file with the following option: +Update `withSentryConfig` in your `next.config.(js|mjs)` file with the following options: ```javascript {tabTitle:ESM} {filename:next.config.mjs} export default withSentryConfig(nextConfig, { @@ -441,19 +431,17 @@ module.exports = withSentryConfig(nextConfig, { }); ``` - - If the route configured with `tunnelRoute` is intercepted by your Next.js - middleware, the client-side events recording will fail. You can exclude the - tunnel route by adding a negative matcher to your middleware like this: - `(?!monitoring-tunnel)`. + + Client-side event recording will fail if your Next.js middleware intercepts + the configured route. To prevent this, exclude the tunnel route by adding a + negative matcher to your middleware like `(?!monitoring-tunnel)`. ## Step 6: Instrument Vercel Cron Jobs (Optional) -If you have configured [Vercel Cron Jobs](https://vercel.com/docs/cron-jobs) you can set the `automaticVercelMonitors` option to automatically create [Cron Monitors](/product/crons/) in Sentry. +You can automatically create [Cron Monitors](/product/crons/) in Sentry if you have configured [Vercel cron jobs](https://vercel.com/docs/cron-jobs). + +Update `withSentryConfig` in your `next.config.(js|mjs)` file with the following option: ```javascript {tabTitle:ESM} {filename:next.config.mjs} export default withSentryConfig(nextConfig, { @@ -469,15 +457,14 @@ module.exports = withSentryConfig(nextConfig, { -Automatic instrumentation of Vercel cron jobs currently only works for the Pages Router. App Router route handlers are not yet supported. +Automatic Vercel cron jobs instrumentation currently only supports the Pages Router. App Router route handlers are not yet supported. ## Step 7: Capture React Component Names (Optional) -You can capture the names of React components in your application, so that you can, for example, see the name of a component that a user clicked on in different Sentry features, like Session Replay and the Performance page. - -Update `withSentryConfig` in your `next.config.js` or `next.config.mjs` with the following option to capture component names: +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: ```javascript {tabTitle:ESM} {filename:next.config.mjs} export default withSentryConfig(nextConfig, { @@ -505,11 +492,11 @@ Check the latest information on [Sentry's support for Turbopack on GitHub](https -Let's test your setup and confirm that Sentry is working properly and sending data to your Sentry project. +Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. ### Issues -To test if Sentry captures errors and creates issues for them in your Sentry project, add a test button to one of your existing pages or create a new one: +To verify that Sentry captures errors and creates issues in your Sentry project, add a test button to an existing page or create a new one: ```jsx + + ); +} +``` + +## Step 5: 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. @@ -402,7 +441,7 @@ Make sure to keep your auth token secret and out of version control. -## Step 5: Avoid Ad Blockers With Tunneling (Optional) +## Step 6: 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. @@ -432,7 +471,114 @@ module.exports = withSentryConfig(nextConfig, { negative matcher to your middleware like `(?!monitoring-tunnel)`. -## Step 6: Instrument Vercel Cron Jobs (Optional) +## 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 `sentry.client.config.js`. 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) You can automatically create [Cron Monitors](/product/crons/) in Sentry if you have configured [Vercel cron jobs](https://vercel.com/docs/cron-jobs). @@ -456,7 +602,7 @@ Automatic Vercel cron jobs instrumentation currently only supports the Pages Rou -## Step 7: Capture React Component Names (Optional) +## Step 9: 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: @@ -477,7 +623,7 @@ module.exports = withSentryConfig(nextConfig, { }); ``` -## Step 8: Verify +## Step 10: Verify