Quick Start: Manual Setup

Learn how to manually set up and configure Sentry in your Next.js application, capture your first errors, and view them in Sentry.

  • A Sentry account and project
  • Be logged in to your Sentry account to have your project's data pre-filled (recommended)
  • Your application up and running

Run the following command for your preferred package manager to add the Sentry SDK to your application:

Copied
npm install @sentry/nextjs --save

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.

Want to learn more about these features?

You can add or remove features at any time, but setting them up now will save you the effort of configuring them manually later.

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:

next.config.js
Copied
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 `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",

  // Automatically tree-shake Sentry logger statements to reduce bundle size
  disableLogger: true,
});
Avoid ad blockers with tunneling

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.

sentry.client.config.(js|ts)
Copied
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  // Replay may only be enabled for the client-side
  integrations: [Sentry.replayIntegration()],

  // 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,

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

  // ...

  // Note: if you want to override the automatic release value, do not set a
  // `release` value here - use the environment variable `SENTRY_RELEASE`, so
  // that it will also get attached to your source maps
});

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.

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:

instrumentation.(js|ts)
Copied
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");
  }
}

Make sure that the import statements point to your newly created sentry.server.config.(js|ts) and sentry.edge.config.(js|ts) files.

To capture React render errors you need to add Error components for the App Router.

Create a Custom Next.js Global Error component for the App router:

global-error.tsx
Copied
"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 (
    <html>
      <body>
        {/* `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. */}
        <NextError statusCode={0} />
      </body>
    </html>
  );
}

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, which allows reporting errors to Sentry.

To report errors using the onRequestError hook, pass all arguments to the captureRequestError function:

instrumentation.ts
Copied
import * as Sentry from "@sentry/nextjs";

export const onRequestError = Sentry.captureRequestError;

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.

Update withSentryConfig in your next.config.js or next.config.mjs file with the following additions:

next.config.mjs
Copied
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,
});

Alternatively, you can set the SENTRY_AUTH_TOKEN environment variable in your .env file:

.env
Copied
SENTRY_AUTH_TOKEN=sntrys_YOUR_TOKEN_HERE

If you have configured Vercel Cron Jobs you can set the automaticVercelMonitors option to automatically create Cron Monitors in Sentry.

next.config.mjs
Copied
export default withSentryConfig(nextConfig, {
  automaticVercelMonitors: true,
});

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.

Update withSentryConfig in your next.config.js or next.config.mjs with the following addition to capture component names:

next.config.mjs
Copied
export default withSentryConfig(nextConfig, {
  reactComponentAnnotation: {
    enabled: true,
  },
});

Are you developing with Turbopack?

Let's test your setup and confirm that Sentry is working properly and sending data to your Sentry project.

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:

Copied
<button
  type="button"
  onClick={() => {
    throw new Error("Sentry Test Error");
  }}
>
  Break the world
</button>;

To see whether Sentry tracing is working, create a test route that throws an error:

Copied
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 the onClick event in your button to call the API route and throw an error if the API response is not ok:

Copied
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");
	  }
	});
  }

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:

  • a frontend error
  • an error within the API route

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.

Now, head over to your project on 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?

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.

Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are:

Did you experience any issues with this guide?
Was this helpful?
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").