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.
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.
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.
Run the following command for your preferred package manager to add the Sentry SDK to your application:
npm install @sentry/nextjs --save
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
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.
Note
There are slight differences between these files since they run in different places (browser, server, edge), so copy them carefully!
sentry.client.config.(js|ts)
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
});
Tip
We recommend you include your Data Source Name (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.
For Next.js versions <15
enable the Next.js instrumentation hook by setting the experimental.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:
instrumentation.(js|ts)
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
"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>
);
}
Note
You can also add Error components for the Pages Router, which you can learn more about here (LINK!).
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
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
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
SENTRY_AUTH_TOKEN=sntrys_YOUR_TOKEN_HERE
Important
Make sure to keep your auth token secret and don't commit it to version control.
If you have configured Vercel Cron Jobs you can set the automaticVercelMonitors
option to automatically create Cron Monitors in Sentry.
next.config.mjs
export default withSentryConfig(nextConfig, {
automaticVercelMonitors: true,
});
Automatic instrumentation of Vercel cron jobs currently only works for the Pages Router. App Router route handlers are not yet supported.
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:
next.config.mjs
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:
<button
type="button"
onClick={() => {
throw new Error("Sentry Test Error");
}}
>
Break the world
</button>;
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.
To see whether Sentry tracing is working, create a test route that throws an error:
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
:
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 a 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).
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.
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 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
- Learn how to manually capture errors
- Continue to customize your configuration
- Learn more about our Vercel integration
Did you experience any issues with this guide?
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").