diff --git a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx index 0ccaee2372c5e..d9a0fecec3be4 100644 --- a/docs/platforms/javascript/guides/nextjs/manual-setup.mdx +++ b/docs/platforms/javascript/guides/nextjs/manual-setup.mdx @@ -1,12 +1,42 @@ --- -title: Manual Setup +title: "Manual Setup" sidebar_order: 1 -description: "Learn how to set up the SDK manually." +description: "Learn how to manually set up Sentry in your Next.js app and capture your first errors." --- -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. + + For the fastest setup, we recommend using the [wizard + installer](/platforms/javascript/guides/nextjs). + + + + +## Step 1: Install + +Choose the features you want to configure, and this guide will show you how: + + + + -## Installation +- [**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. + + + +### Install the Sentry SDK + +Run the command for your preferred package manager to add the Sentry SDK to your application: ```bash {tabTitle:npm} npm install @sentry/nextjs --save @@ -20,13 +50,11 @@ 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. +## Step 2: Configure -## Extend your Next.js Configuration +### Apply Instrumentation to Your App -Use `withSentryConfig` to extend the default Next.js options. This will apply instrumentation to your application. - -Include the following in your `next.config.js` or `next.config.mjs`: +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"); @@ -40,10 +68,12 @@ 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 `true` to suppress logs + silent: !process.env.CI, - silent: false, // Can be used to suppress logs + // Automatically tree-shake Sentry logger statements to reduce bundle size + disableLogger: true, }); ``` @@ -59,29 +89,25 @@ 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 `true` to suppress logs + silent: !process.env.CI, - 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 +### Initialize Sentry Client-Side and Server-Side SDKs -`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`. +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: - - Note that this option is unstable and its API may include breaking changes in - any release. + + These files run in different environments (browser, server, edge) and are + slightly different, so copy them carefully. -## Create Initialization Config Files - -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! - -```javascript {tabTitle:Client} {filename:sentry.client.config.(js|ts)} +```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({ @@ -103,15 +129,13 @@ Sentry.init({ 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 }); ``` -```javascript {tabTitle:Server} {filename:sentry.server.config.(js|ts)} +```javascript {tabTitle:Server} {filename:sentry.server.config.(js|ts)} {"onboardingOptions": {"performance": "5-11"}} import * as Sentry from "@sentry/nextjs"; Sentry.init({ @@ -132,7 +156,7 @@ Sentry.init({ }); ``` -```javascript {tabTitle:Edge} {filename:sentry.edge.config.(js|ts)} +```javascript {tabTitle:Edge} {filename:sentry.edge.config.(js|ts)} {"onboardingOptions": {"performance": "5-11"}} import * as Sentry from "@sentry/nextjs"; Sentry.init({ @@ -153,16 +177,15 @@ 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`. - -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`. + + 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`. -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: +### Register Sentry Server-Side SDK Initialization + +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() { @@ -176,15 +199,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. + -## 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 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"; @@ -241,12 +268,11 @@ export default function GlobalError({ error }) { #### Errors from Nested React Server Components -_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"; @@ -260,16 +286,17 @@ 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"; import type { Instrumentation } from "next"; export const onRequestError: Instrumentation.onRequestError = (...args) => { - Sentry.captureRequestError(...args); + Sentry.captureRequestError(...args); - // ... additional logic here + // ... additional logic here }; ``` @@ -277,17 +304,19 @@ export const onRequestError: Instrumentation.onRequestError = (...args) => { import * as Sentry from "@sentry/nextjs"; export const onRequestError = (...args) => { - Sentry.captureRequestError(...args); + Sentry.captureRequestError(...args); - // ... additional logic here + // ... 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: +### Pages Router -```TypeScript {filename:_error.tsx} +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"; import type { NextPage } from "next"; import type { ErrorProps } from "next/error"; @@ -309,11 +338,13 @@ CustomErrorComponent.getInitialProps = async (contextData) => { export default CustomErrorComponent; ``` -```JavaScript {filename:_error.jsx} +```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 = (props) => { +const CustomErrorComponent: NextPage = (props) => { return ; }; @@ -329,7 +360,7 @@ CustomErrorComponent.getInitialProps = async (contextData) => { export default CustomErrorComponent; ``` -## Instrument Next.js Server Actions +## Step 4: Instrument Next.js Server Actions (Optional) _Requires `@sentry/nextjs` SDK version `7.81.0` or newer._ @@ -368,83 +399,79 @@ export default function ServerComponent() { } ``` -## Configure Source Maps +## Step 5: Add Readable Stack Traces With Source Maps (Optional) -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. +Sentry can automatically provide readable stack traces for errors using source maps, requiring a Sentry auth token. -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 your `next.config.(js|mjs)` file with the following options: ```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, + // 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, + // 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, set the `SENTRY_AUTH_TOKEN` environment variable in your `.env` file: ```sh {filename:.env} SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ ``` -## Configure Tunneling to avoid Ad-Blockers + -You might notice that Sentry events are sometimes blocked by ad blockers. -Ad blockers can be circumvented by using **tunneling**. +Make sure to keep your auth token secret and out of version control. -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: + + +## 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. + +Update `withSentryConfig` in your `next.config.(js|mjs)` file with the following options: ```javascript {tabTitle:ESM} {filename:next.config.mjs} export default withSentryConfig(nextConfig, { - tunnelRoute: "/monitoring-tunnel", + // 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, { - tunnelRoute: "/monitoring-tunnel", + // 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", }); ``` -Setting this option will add an API endpoint to your application that is used to forward Sentry events to the Sentry servers. - -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)` - + + 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)`. -Please note that this option will tunnel Sentry events through your Next.js application so you might experience increased server usage. - -The `tunnelRoute` option does currently not work with self-hosted Sentry instances. - -Learn more about tunneling in the troubleshooting section. - -## Configure Server-side Auto-instrumentation +## 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. @@ -546,15 +573,16 @@ module.exports = withSentryConfig(nextConfig, { }); ``` -### Instrumentation of Vercel Cron Jobs +### Opt Out of Sentry SDK bundling in Client- or Server-Side -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). +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) -Automatic instrumentation of Vercel cron jobs currently only works for the Pages Router. App Router route handlers are not yet supported. +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, { @@ -568,24 +596,139 @@ module.exports = withSentryConfig(nextConfig, { }); ``` -### Opt Out of Sentry SDK bundling in Client- or Server-Side + -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`. +Automatic Vercel cron jobs instrumentation currently only supports the Pages Router. App Router route handlers are not yet supported. + + -## Disable the Sentry SDK Debug Logger to Save Bundle Size +## Step 9: Capture React Component Names (Optional) -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. +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, { - disableLogger: true, + reactComponentAnnotation: { + enabled: true, + }, }); ``` ```javascript {tabTitle:CJS} {filename:next.config.js} module.exports = withSentryConfig(nextConfig, { - disableLogger: true, + reactComponentAnnotation: { + enabled: true, + }, }); ``` + +## Step 10: Verify + + + +Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. + +### Issues + +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 + +``` + + + Open the page in a browser (for most Next.js applications, this will be at + localhost) and click the button to trigger a frontend error. + + + + +Errors triggered from within your browser's developer tools (like the browser console) are sandboxed, so they will not trigger Sentry's error monitoring. + + + + +### Tracing + +To test tracing, create a test API route like `/api/sentry-example-api`: + +```javascript +import { NextResponse } from "next/server"; +export const dynamic = "force-dynamic"; + +// 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..." }); +} +``` + +Next, update your test button to call this route and throw an error if the response isn't `ok`: + +```jsx +; +``` + +Open the page in a browser (for most Next.js applications, this will be at localhost) and click the button to trigger two errors: + +- a frontend error +- an error within the API route + +Additionally, this starts a performance trace to measure the time it takes for the API request to complete. + + + +### View Captured Data in Sentry + +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). + + + +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. + + + +## Next Steps + +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 +- 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/) + + + +- 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/) + +