KEMBAR78
# Manual Setup | Sentry for Next.js For the fastest setup, we recommend using the [wizard installer](https://docs.sentry.io/platforms/javascript/guides/nextjs.md). ## [Prerequisites](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#prerequisites) You need: * A Sentry [account](https://sentry.io/signup/) and [project](https://docs.sentry.io/product/projects.md) * Your application up and running ## [Step 1: Install](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#step-1-install) Choose the features you want to configure, and this guide will show you how: Error Monitoring\[ ]Logs\[ ]Session Replay\[ ]Tracing\[ ]User Feedback Want to learn more about these features? * [**Issues**](https://docs.sentry.io/product/issues.md) (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**](https://docs.sentry.io/product/tracing.md): 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**](https://docs.sentry.io/product/explore/session-replay/web.md): 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. * [**Logs**](https://docs.sentry.io/product/explore/logs.md): Centralize and analyze your application logs to correlate them with errors and performance issues. Search, filter, and visualize log data to understand what's happening in your applications. ### [Install the Sentry SDK](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#install-the-sentry-sdk) Run the command for your preferred package manager to add the Sentry SDK to your application: ```bash npm install @sentry/nextjs --save ``` ## [Step 2: Configure](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#step-2-configure) ### [Apply Instrumentation to Your App](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#apply-instrumentation-to-your-app) Extend your app's default Next.js options by adding `withSentryConfig` into your `next.config.(js|mjs)` file: `next.config.js` ```JavaScript const { withSentryConfig } = require("@sentry/nextjs"); const nextConfig = { // Your existing Next.js configuration }; // Make sure adding Sentry options is the last code to run before exporting module.exports = withSentryConfig(nextConfig, { org: "example-org", project: "example-project", // Only print logs for uploading source maps in CI // Set to `true` to suppress logs silent: !process.env.CI, // Automatically tree-shake Sentry logger statements to reduce bundle size disableLogger: true, }); ``` Additional Configuration for App Router on Next.js 14 In order to enable distributed tracing for App Router on Next.js 14 you need to add or modify the `generateMetadata` function of your root layout: `app/layout.tsx` ```typescript import * as Sentry from "@sentry/nextjs"; import type { Metadata } from "next"; export function generateMetadata(): Metadata { return { // ... your existing metadata other: { ...Sentry.getTraceData(), }, }; } ``` ### [Initialize Sentry Client-Side and Server-Side SDKs](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#initialize-sentry-client-side-and-server-side-sdks) Create three files in your application's root directory: * `sentry.server.config.(js|ts)` * `sentry.edge.config.(js|ts)` * `instrumentation-client.(js|ts)` * If you previously had a file called `sentry.client.config.(js|ts)`, you can safely rename this to `instrumentation-client.(js|ts)` for all Next.js versions. Add the following initialization code into each respective file: ##### Note These files run in different environments (browser, server, edge) and are slightly different, so copy them carefully. `instrumentation-client.(js|ts)` ```javascript import * as Sentry from "@sentry/nextjs"; Sentry.init({ dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", // Adds request headers and IP for users, for more info visit: // https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#sendDefaultPii sendDefaultPii: true, // performance // Set tracesSampleRate to 1.0 to capture 100% // of transactions for tracing. // We recommend adjusting this value in production // Learn more at // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate tracesSampleRate: 1.0, // performance integrations: [ // session-replay // Replay may only be enabled for the client-side Sentry.replayIntegration(), // session-replay // user-feedback Sentry.feedbackIntegration({ // Additional SDK configuration goes in here, for example: colorScheme: "system", }), // user-feedback ], // session-replay // Capture Replay for 10% of all sessions, // plus for 100% of sessions with an error // Learn more at // https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration replaysSessionSampleRate: 0.1, replaysOnErrorSampleRate: 1.0, // session-replay // logs // Enable logs to be sent to Sentry enableLogs: true, // logs // 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 }); // This export will instrument router navigations, and is only relevant if you enable tracing. // `captureRouterTransitionStart` is available from SDK version 9.12.0 onwards export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; ``` ##### Tip Include your DSN directly in these files, or use a *public* environment variable like `NEXT_PUBLIC_SENTRY_DSN`. ### [Register Sentry Server-Side SDK Initialization](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#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: `instrumentation.(js|ts)` ```javascript export async function register() { if (process.env.NEXT_RUNTIME === "nodejs") { await import("./sentry.server.config"); } if (process.env.NEXT_RUNTIME === "edge") { await import("./sentry.edge.config"); } } ``` Opt out of Sentry SDK bundling on client- or server-side. If you want the Sentry SDK to be available on the server side and not on the client side, simply delete `instrumentation-client.(js|ts)`. This will prevent webpack from pulling in the Sentry-related files when generating the browser bundle. Similarly, if you want to opt out of server-side SDK bundling, delete the `sentry.server.config.js` and `sentry.edge.config.js` files. Make sure to remove any imports of these files from `instrumentation.ts`. ## [Step 3: Capture React Render Errors](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#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. ### [App Router](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#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): `global-error.tsx` ```tsx "use client"; import * as Sentry from "@sentry/nextjs"; import NextError from "next/error"; import { useEffect } from "react"; export default function GlobalError({ error, }: { error: Error & { digest?: string }; }) { useEffect(() => { Sentry.captureException(error); }, [error]); return ( {/* `NextError` is the default Next.js error page component. Its type definition requires a `statusCode` prop. However, since the App Router does not expose status codes for errors, we simply pass 0 to render a generic error message. */} ); } ``` #### [Errors from Nested React Server Components](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#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`](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: `instrumentation.ts` ```TypeScript import * as Sentry from "@sentry/nextjs"; export const onRequestError = Sentry.captureRequestError; ``` Need additional logic within \`onRequestError\`? You can call `captureRequestError` with all arguments passed to `onRequestError`: `instrumentation.ts` ```TypeScript import * as Sentry from "@sentry/nextjs"; import type { Instrumentation } from "next"; export const onRequestError: Instrumentation.onRequestError = (...args) => { Sentry.captureRequestError(...args); // ... additional logic here }; ``` ### [Pages Router](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#pages-router) 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: `_error.tsx` ```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; ``` ## [Step 4: Add Readable Stack Traces With Source Maps (Optional)](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#step-4-add-readable-stack-traces-with-source-maps-optional) Sentry can automatically provide readable stack traces for errors using source maps, requiring a Sentry auth token. Update your `next.config.(js|mjs)` file with the following options: `next.config.mjs` ```javascript export default withSentryConfig(nextConfig, { org: "example-org", project: "example-project", // 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, }); ``` Set the `SENTRY_AUTH_TOKEN` environment variable in your `.env` file: `.env` ```sh SENTRY_AUTH_TOKEN=sntrys_YOUR_TOKEN_HERE ``` ##### Important Make sure to keep your auth token secret and out of version control. ## [Step 5: Avoid Ad Blockers With Tunneling (Optional)](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#step-5-avoid-ad-blockers-with-tunneling-optional) You can prevent ad blockers from blocking Sentry events using tunneling. Use the `tunnelRoute` option to add an API endpoint in your application that forwards Sentry events to Sentry servers. For better ad-blocker evasion, you can either: * Set `tunnelRoute: true` to automatically generate a random tunnel route for each build, making it harder for ad-blockers to detect and block monitoring requests * Set `tunnelRoute: "/my-tunnel-route"` to use a static route of your choosing `next.config.mjs` ```javascript 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: true, // Generates a random route for each build (recommended) }); ``` Using Next.js middleware on Turbopack If you're using Turbopack, client-side event recording will fail if your Next.js middleware intercepts the configured tunnel route. To fix this, set the route to a fixed string (like `/error-monitoring`) and add a negative matcher like `(?!error-monitoring)` in your middleware to exclude the tunnel route. If you're not using Turbopack, Sentry will automatically skip the tunnel route in your middleware. ## [Step 6: Instrument Vercel Cron Jobs (Optional)](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#step-6-instrument-vercel-cron-jobs-optional) You can automatically create [Cron Monitors](https://docs.sentry.io/product/crons.md) 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: `next.config.mjs` ```javascript export default withSentryConfig(nextConfig, { automaticVercelMonitors: true, }); ``` 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)](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#step-7-capture-react-component-names-optional) You can capture React component names to see which component a user clicked on in Sentry features like Session Replay. Update `withSentryConfig` in your `next.config.(js|mjs)` file with the following option: `next.config.mjs` ```javascript export default withSentryConfig(nextConfig, { reactComponentAnnotation: { enabled: true, }, }); ``` ## [Step 8: Verify](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#step-8-verify) Are you using Turbopack? The Sentry SDK fully supports Turbopack production builds (`next build --turbopack`) starting with `@sentry/nextjs@10.13.0`. The minimum required Next.js version is `next@15.4.1`. Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. ### [Issues](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#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. ##### Important 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](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#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](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#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). Need help locating the captured errors in your Sentry project? 1. Open the [**Issues**](https://sentry.io/issues) page and select an error from the issues list to view the full details and context of this error. For more details, see this [interactive walkthrough](https://docs.sentry.io/product/sentry-basics/integrate-frontend/generate-first-error.md#ui-walkthrough). 2. Open the [**Traces**](https://sentry.io/explore/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](https://docs.sentry.io/product/sentry-basics/distributed-tracing/generate-first-error.md#ui-walkthrough). 3. Open the [**Replays**](https://sentry.io/explore/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. 4. Open the [**Logs**](https://sentry.io/explore/logs) page and filter by service, environment, or search keywords to view log entries from your application. For an interactive UI walkthrough, click [here](https://docs.sentry.io/product/explore/logs.md#overview). ## [Next Steps](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#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: * Learn about [instrumenting Next.js server actions](https://docs.sentry.io/platforms/javascript/guides/nextjs/apis.md#server-actions) * Configure [server-side auto-instrumentation](https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/build.md#nextjs-specific-options) * Learn how to [manually capture errors](https://docs.sentry.io/platforms/javascript/guides/nextjs/usage.md) * Continue to [customize your configuration](https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration.md) * Learn more about our [Vercel integration](https://docs.sentry.io/organization/integrations/deployment/vercel.md) Are you having problems setting up the SDK? * If you encountered issues with setting up Sentry manually, [try our installation wizard](https://docs.sentry.io/platforms/javascript/guides/nextjs.md) * [Get support](https://sentry.zendesk.com/hc/en-us/)