Next.js

Learn how to set up and configure Sentry in your Next.js application using the installation wizard, capture your first errors, logs and traces 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 .cursor/rules directory, or the contents in the AGENTS.md or .cursorrules (legacy) files.

rules.mdc
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 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 `Sentry.logger`
- 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.server.config.ts` and the edge initialization is in `sentry.edge.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://[email protected]/0",

  enableLogs: true,
});
```

### Logger Integration

```javascript
Sentry.init({
  dsn: "https://[email protected]/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:

Run the Sentry wizard to automatically configure Sentry in your Next.js application:

Copied
npx @sentry/wizard@latest -i nextjs

The wizard will prompt you to select features. Choose the ones you want to enable:

Prefer to set things up yourself? Check out the Manual Setup guide.

The wizard configured Sentry for all Next.js runtime environments and created files to test your setup.

Next.js runs code in different environments. The wizard creates separate initialization files for each:

  • Client (instrumentation-client.ts) — Runs in the browser
  • Server (sentry.server.config.ts) — Runs in Node.js
  • Edge (sentry.edge.config.ts) — Runs in edge runtimes
instrumentation-client.ts
Copied
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: "___PUBLIC_DSN___",

  // Adds request headers and IP for users
  sendDefaultPii: true,
  // ___PRODUCT_OPTION_START___ performance
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
  // ___PRODUCT_OPTION_END___ performance
  // ___PRODUCT_OPTION_START___ session-replay
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  // ___PRODUCT_OPTION_END___ session-replay
  // ___PRODUCT_OPTION_START___ logs
  enableLogs: true,
  // ___PRODUCT_OPTION_END___ logs
    // ___PRODUCT_OPTION_START___ session-replay
    Sentry.replayIntegration(),
    // ___PRODUCT_OPTION_END___ session-replay
});

The instrumentation.ts file registers your server and edge configurations with Next.js.

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

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

export const onRequestError = Sentry.captureRequestError;

Your next.config.ts is wrapped with withSentryConfig to enable source map uploads, tunneling (to avoid ad-blockers), and other build-time features.

next.config.ts
Copied
import { withSentryConfig } from "@sentry/nextjs";

export default withSentryConfig(nextConfig, {
  org: "___ORG_SLUG___",
  project: "___PROJECT_SLUG___",

  // Upload source maps for readable stack traces
  authToken: process.env.SENTRY_AUTH_TOKEN,

  // Route Sentry requests through your server (avoids ad-blockers)
  tunnelRoute: "/monitoring",

  silent: !process.env.CI,
});

The wizard creates app/global-error.tsx to capture React rendering errors in your App Router application.

app/global-error.tsx
Copied
"use client";

import * as Sentry from "@sentry/nextjs";
import { useEffect } from "react";

export default function GlobalError({
  error,
}: {
  error: Error & { digest?: string };
}) {
  useEffect(() => {
    Sentry.captureException(error);
  }, [error]);

  return (
    <html>
      <body>
        <h1>Something went wrong!</h1>
      </body>
    </html>
  );
}

The wizard creates .env.sentry-build-plugin with your auth token for source map uploads. This file is automatically added to .gitignore.

For CI/CD, set the SENTRY_AUTH_TOKEN environment variable in your build system.

.env.sentry-build-plugin
Copied
SENTRY_AUTH_TOKEN=sntrys_eyJ...

The wizard creates /sentry-example-page with a button that triggers a test error. Use this to verify your setup.

Copied
app/
├── sentry-example-page/
│   └── page.tsx       # Test page with error button
└── api/
    └── sentry-example-api/
        └── route.ts   # Test API route

The example page tests all your enabled features with a single action:

  1. Start your dev server:
Copied
npm run dev
  1. Visit localhost:3000/sentry-example-page

  2. Click "Throw Sample Error"

ErrorsOpen Issues

You should see "This is a test error" with a full stack trace pointing to your source code.

TracingOpen Traces

You should see the page load trace and the button click span. Learn more about custom spans.

Session ReplayOpen Replays

Watch a video-like recording of your session, including the moment the error occurred. Learn more about Session Replay configuration.

LogsOpen Logs NEW

See structured log entries from your application. You can send logs from anywhere:

Copied
Sentry.logger.info("User action", { userId: "123" });
Sentry.logger.warn("Slow response", { duration: 5000 });
Sentry.logger.error("Operation failed", { reason: "timeout" });

Learn more about Logs configuration.

Are you having problems setting up the SDK?

If you're using Next.js Cache Components, you may encounter errors like:

Copied
Accessing random cryptographic values synchronously in a Server Component requires reading one of these data sources first...

Using generateMetadata in page components with Turbopack and the Sentry SDK is currently not supported. (Tracking issue)

Workarounds:

  • Remove generateMetadata from affected page components
  • Disable server-side tracing by removing or renaming your instrumentation.ts file

Cache Components are not supported when using webpack. (Tracking issue)

Workarounds:

  • Switch to Turbopack (note the generateMetadata limitation above)
  • Disable server-side tracing by removing or renaming your instrumentation.ts file

You've successfully integrated Sentry into your Next.js application! Here's what to explore next:

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").