Getting Started with Sentry in Next.js
Get started with monitoring errors, sending structure logs, replays, and sending traces and spans with span attributes within your in your Next.js application.
Unlike the Quick Start which focuses on the fastest path to getting started with Sentry, this guide focuses on getting you up and running with the core of Sentry's capabilities.
By the end of this guide, you'll be able to:
- Install the Sentry SDK using the Sentry installation wizard
- Manually capture errors or issues beyond the automated capture methods
- Sent Structured Logs to from your application to Sentry
- Configure masking propers within Replays
- Implement tracing and send custom spans with attributes and metrics
npx @sentry/wizard@latest -i nextjs
The wizard will guide you through the setup process, asking you to enable additional (optional) Sentry features for your application beyond error monitoring.
During this setup process, you'll be prompted to either create your project or select an existing project within Sentry.
If you want to expand on your Sentry configuration by adding additional functionality, or manually instrument your application, here are the configuration files the wizard would create. This configuration assumes you enabled all of the functionality the wizard proposed including replays, logs, and tracing.
instrumentation-client.(js|ts)
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,
integrations: [
// performance
Sentry.browserTracingIntegration(),
// performance
// session-replay
// Replay may only be enabled for the client-side
Sentry.replayIntegration(),
// session-replay
],
// logs
// Enable logs to be sent to Sentry
enableLogs: true,
// logs
// 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
// session-replay
// Capture Replay for 10% of all
// 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
});
sentry.server.config.(js|ts)
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,
// logs
// Enable logs to be sent to Sentry
enableLogs: true,
// logs
// 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
});
For detailed manual setup instructions, see our manual setup guide.
By default, Sentry captures errors and exceptions automatically within your application.For times where you want to manually capture, use Sentry.captureException()
. This can be used anywhere you catch errors — on the server or in client components — to send exceptions to Sentry with full context.
Server-side examples:
app/api/example/route.(ts|js)
import * as Sentry from "@sentry/nextjs";
export async function GET() {
try {
// Your code that might throw
throw new Error("Failed to fetch data");
} catch (err) {
Sentry.captureException(err);
// Optionally keep propagating the error
throw err;
}
}
Client-side example:
app/example-client-component.(tsx|jsx)
"use client";
import * as Sentry from "@sentry/nextjs";
export function DangerousButton() {
const onClick = async () => {
try {
// Code that might throw (sync or async)
throw new Error("User action failed");
} catch (err) {
Sentry.captureException(err);
// Optional: rethrow if you rely on React error boundaries
throw err;
}
};
return <button onClick={onClick}>Do risky thing</button>;
}
Server-side example (API route):
pages/api/example.(ts|js)
import * as Sentry from "@sentry/nextjs";
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
// ...might throw
res.status(200).json({ ok: true });
} catch (err) {
Sentry.captureException(err);
// Respond or rethrow based on your needs
res.status(500).json({ error: "Internal Server Error" });
}
}
Client-side example:
components/DangerousButton.(tsx|jsx)
import * as Sentry from "@sentry/nextjs";
export function DangerousButton() {
const onClick = () => {
try {
throw new Error("Something went wrong");
} catch (err) {
Sentry.captureException(err);
// Optional: rethrow to trigger error boundaries
throw err;
}
};
return <button onClick={onClick}>Click me</button>;
}
Structured logging lets users send text-based log information from their applications to Sentry. Once in Sentry, these logs can be viewed alongside relevant errors, searched by text-string, or searched using their individual attributes.
Use Sentry's logger to capture structured logs with meaningful attributes that help you debug issues and understand user behavior.
import * as Sentry from "@sentry/nextjs";
const { logger } = Sentry;
logger.info("User completed checkout", {
userId: 123,
orderId: "order_456",
amount: 99.99,
});
logger.error("Payment processing failed", {
errorCode: "CARD_DECLINED",
userId: 123,
attemptCount: 3,
});
logger.warn(logger.fmt`Rate limit exceeded for user: ${123}`);
Replays allow you to see video-like reproductions of user sessions.
By default, Session Replay masks sensitive data to protect privacy and PII data. If needed, you can modify the replay configurations in your client-side Sentry initialization to show (unmask) specific content that's safe to display.
Use caution when choosing what content to unmask within your application. This content displays in Replays may contain sensitive information or PII data.
instrumentation-client.(js|ts)
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
Sentry.replayIntegration({
// This will show the content of the div with the class "reveal-content" and the span with the data-safe-to-show attribute
unmask: [".reveal-content", "[data-safe-to-show]"],
// This will show all text content in replays. Use with caution.
maskAllText: false,
// This will show all media content in replays. Use with caution.
blockAllMedia: false,
}),
],
// Only capture replays for 10% of sessions
replaysSessionSampleRate: 0.1,
// Capture replays for 100% of sessions with an error
replaysOnErrorSampleRate: 1.0,
});
Tracing allows you to monitor interactions between multiple services or applications. Create custom spans to measure specific operations and add meaningful attributes. This helps you understand performance bottlenecks and debug issues with detailed context.
import * as Sentry from "@sentry/nextjs";
async function processUserData(userId) {
return await Sentry.startSpan(
{
name: "Process User Data",
op: "function",
attributes: {
userId: userId,
operation: "data_processing",
version: "2.1",
},
},
async () => {
const userData = await fetch(`/api/user?id=${userId}`).then((r) =>
r.json(),
);
return await Sentry.startSpan(
{
name: "Transform Data",
op: "transform",
attributes: {
recordCount: userData.length,
transformType: "normalize",
},
},
() => transformUserData(userData),
);
},
);
}
const span = Sentry.getActiveSpan();
if (span) {
span.setAttributes({
cacheHit: true,
region: "us-west-2",
performanceScore: 0.95,
});
}
If you haven't tested your Sentry configuration yet, let's do it now. You can confirm that Sentry is working properly and sending data to your Sentry project by using the example page and route created by the installation wizard:
- Open the example page
/sentry-example-page
in your browser. For most Next.js applications, this will be at localhost. - Click the "Throw error" button. This 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.
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:
- Learn more about enriching the data (events) you send to Sentry
- Explore more about configuring Structured Logs in your application
- See advanced configurations for Replays
- Setup and configure Distributed Tracing between the different tiers and services for your application
- Learn how to use the insights views in Sentry to explore performance related information about your application (including the Next.js specific view)
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").