Next.js

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

AI Rules for Code Editors

Sentry provides a set of rules you can use to help your LLM use Sentry correctly. Copy this file and add it to your projects rules configuration. When created as a rules file this should be placed alongside other editor specific rule files. For example, if you are using Cursor, place this file in the .cursorrules directory.

rules.md
Copied
These examples should be used as guidance when configuring Sentry functionality within a project.

# Exception Catching

- Use `Sentry.captureException(error)` to capture an exception and log the error in Sentry.
- Use this in try catch blocks or areas where exceptions are expected

# Tracing Examples

- Spans should be created for meaningful actions within an applications like button clicks, API calls, and function calls
- Use the `Sentry.startSpan` function to create a span
- Child spans can exist within a parent span

## Custom Span instrumentation in component actions

- The `name` and `op` properties should be meaningful for the activities in the call.
- Attach attributes based on relevant information and metrics from the request

```javascript
function TestComponent() {
  const handleTestButtonClick = () => {
    // Create a transaction/span to measure performance
    Sentry.startSpan(
      {
        op: "ui.click",
        name: "Test Button Click",
      },
      (span) => {
        const value = "some config";
        const metric = "some metric";

        // Metrics can be added to the span
        span.setAttribute("config", value);
        span.setAttribute("metric", metric);

        doSomething();
      },
    );
  };

  return (
    <button type="button" onClick={handleTestButtonClick}>
      Test Sentry
    </button>
  );
}
```

## Custom span instrumentation in API calls

- The `name` and `op` properties should be meaningful for the activities in the call.
- Attach attributes based on relevant information and metrics from the request

```javascript
async function fetchUserData(userId) {
  return Sentry.startSpan(
    {
      op: "http.client",
      name: `GET /api/users/${userId}`,
    },
    async () => {
      const response = await fetch(`/api/users/${userId}`);
      const data = await response.json();
      return data;
    },
  );
}
```

# Logs

- Where logs are used, ensure Sentry is imported using `import * as Sentry from "@sentry/nextjs"`
- Enable logging in Sentry using `Sentry.init({ enableLogs: true })`
- Reference the logger using `const { logger } = Sentry`
- Sentry offers a consoleLoggingIntegration that can be used to log specific console error types automatically without instrumenting the individual logger calls

## Configuration

- In NextJS the client side Sentry initialization is in `instrumentation-client.ts`, the server initialization is in `sentry.edge.config.ts` and the edge initialization is in `sentry.server.config.ts`
- Initialization does not need to be repeated in other files, it only needs to happen the files mentioned above. You should use `import * as Sentry from "@sentry/nextjs"` to reference Sentry functionality

### Baseline

```javascript
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

  enableLogs: true,
});
```

### Logger Integration

```javascript
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    // send console.log, console.error, and console.warn calls as logs to Sentry
    Sentry.consoleLoggingIntegration({ levels: ["log", "error", "warn"] }),
  ],
});
```

## Logger Examples

`logger.fmt` is a template literal function that should be used to bring variables into the structured logs.

```javascript
logger.trace("Starting database connection", { database: "users" });
logger.debug(logger.fmt`Cache miss for user: ${userId}`);
logger.info("Updated profile", { profileId: 345 });
logger.warn("Rate limit reached for endpoint", {
  endpoint: "/api/results/",
  isEnterprise: false,
});
logger.error("Failed to process payment", {
  orderId: "order_123",
  amount: 99.99,
});
logger.fatal("Database connection pool exhausted", {
  database: "users",
  activeConnections: 100,
});
```

You need:

In addition to capturing errors, you can monitor interactions between multiple services or applications by enabling tracing. You can also get to the root of an error or performance issue faster, by watching a video-like reproduction of a user session with session replay.

Send structured logs to Sentry and correlate them with errors and traces.

Select which Sentry features you'd like to configure to get the corresponding setup instructions below.

Run the command for your preferred path to add Sentry to your application.

Copied
npx @sentry/wizard@latest -i nextjs

The wizard then guides you through the setup process, asking you to enable additional (optional) Sentry features for your application beyond error monitoring.

Want to learn more about these features?
  • 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: 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: 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: 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.
What does the installation wizard change inside your application?
  • Creates config files with the default Sentry.init() calls for all runtimes (Node.js, Browser, and Edge)
  • Adds a Next.js instrumentation hook to your project (instrumentation.ts)
  • Creates or updates your Next.js config with the default Sentry settings
  • Creates error handling components (global-error.(jsx|tsx) and _error.jsx for the Pages Router) if they don't already exist
  • Creates .sentryclirc with an auth token to upload source maps (this file is automatically added to .gitignore)
  • Adds an example page and route to your application to help verify your Sentry setup

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. Initialize Sentry as early as possible.

instrumentation-client.(js|ts)
Copied
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
    //  user-feedback
    Sentry.feedbackIntegration({
      // Additional SDK configuration goes in here, for example:
      colorScheme: "system",
    }),
    //  user-feedback
  ],
  //  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)
Copied
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.

Make sure runtime errors are surfaced to Sentry using Next.js error components.

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.

Copied
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 for privacy and to protect PII data. You can modify the replay configurations in your client-side Sentry initialization to show (unmask) specific content that's safe to display.

instrumentation-client.(js|ts)
Copied
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.

Copied
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:

  1. Open the example page /sentry-example-page in your browser. For most Next.js applications, this will be at localhost.
  2. 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).

Need help locating the captured errors in your Sentry project?
  1. Open the 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.
  2. Open the 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.
  3. Open the 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 page and filter by service, environment, or search keywords to view log entries from your application. For an interactive UI walkthrough, click here.
Are you using Turbopack?

The Sentry SDK doesn't yet fully support Turbopack production builds (next build --turbopack) as Turbopack production builds are still in alpha.

If you upgraded the Sentry SDK to the latest version and installed Next.js on version 15.3.0 or later, the SDK will capture all data as expected, however, it is currently not possible to apply sourcemaps to Turbopack production builds.

Turbopack in dev-mode (next dev --turbopack) is fully supported for Next.js 15.3.0 and later. To verify your Sentry setup, temporarily remove the --turbo if you're on older Next.js versions.

Check the latest information on Sentry's support for Turbopack on GitHub.

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:

Want to learn more about these features?
  • 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: 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: 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: 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.
Are you having problems setting up the SDK?
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").