---
title: "Manual Setup"
description: "Learn how to set up and configure Sentry in your Next.js application and capture your first events in Sentry."
url: https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
---

# Manual Setup for Next.js

Runtime

* [Node.js (current page)](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md)
* [Cloudflare](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/cloudflare.md)
* [Bun](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/bun.md)
* [Deno](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/deno.md)

Looking for automatic setup with `sentry init` or the Next.js wizard? Follow the [Next.js quickstart](https://docs.sentry.io/platforms/javascript/guides/nextjs.md) instead. Continue with this guide to set up Sentry manually.

This guide covers manual setup for **Next.js 15+ with Turbopack and App Router**. For other setups, see:

* [Pages Router Setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.md) - For applications using the Pages Router
* [Webpack Setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/webpack-setup.md) - For applications not using Turbopack

## [Prerequisites](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#prerequisites)

You need:

* A Next.js application on version 14 or higher
* Node.js 20.19.0 or higher
* A Sentry [account](https://sentry.io/signup/) and [project](https://docs.sentry.io/product/projects.md)

## [Install](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#install)

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

```bash
npm install @sentry/nextjs --save
```

*Other available variations of the above snippet: yarn, pnpm*

## [Configure](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#configure)

**Error Monitoring** starts working as soon as you call `Sentry.init()`. **Logs** and **Application Metrics** need no extra configuration, and you'll learn how to send them in steps [#3](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#send-logs) and [#4](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#send-application-metrics-). This guide also enables **Tracing**, **Session Replay**, and **User Feedback**.

Want to learn more about these features?

* [**Issues**](https://docs.sentry.io/product/issues.md) (always enabled): Sentry's core error monitoring product that automatically reports errors, uncaught exceptions, and crashes. If you have something that looks like an exception, Sentry can capture it.
* [**Tracing**](https://docs.sentry.io/product/tracing.md): 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. On the server, this includes [Agent Tracing](https://docs.sentry.io/product/agents.md): supported AI libraries are instrumented automatically, so you can see model calls, tool executions, and token usage.
* [**Session Replay**](https://docs.sentry.io/product/session-replay.md): Get to the root cause of an issue faster by viewing a video-like reproduction of what users saw in your app before, during, and after the problem.
* [**Logs**](https://docs.sentry.io/product/logs.md): 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.
* [**Application Metrics**](https://docs.sentry.io/product/metrics.md) (always enabled): Track and analyze custom application metrics, such as response times and database query durations, to understand trends and patterns in your application's performance and behavior over time.
* [**User Feedback**](https://docs.sentry.io/product/user-feedback.md): Collect feedback directly from users when they encounter errors, allowing them to describe what happened and provide context that helps you understand and resolve issues faster.

### [Apply Instrumentation to Your App](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#apply-instrumentation-to-your-app)

Extend your app's default Next.js options by adding `withSentryConfig` into your `next.config.ts` file.

```typescript
import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs/config";

const nextConfig: NextConfig = {
  // Your existing Next.js configuration
};

export default withSentryConfig(nextConfig, {
  org: "<your-org-slug>",
  project: "<your-project-slug>",

  // Only print logs for uploading source maps in CI
  silent: !process.env.CI,
});
```

### [Initialize Sentry SDKs](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#initialize-sentry-sdks)

Create the following files in your application's root directory (or `src` folder if you have one):

* `instrumentation-client.ts` - Client-side SDK initialization
* `sentry.server.config.ts` - Server-side SDK initialization
* `sentry.edge.config.ts` - Edge runtime SDK initialization

##### Tip

Include your DSN directly in these files, or use a *public* environment variable like `NEXT_PUBLIC_SENTRY_DSN`.

The snippets also turn on:

* Tracing: via [`tracesSampleRate`](https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options.md#tracesSampleRate) in all three files
* Session Replay: via `replayIntegration()`, sampled with [`replaysSessionSampleRate`](https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options.md#replaysSessionSampleRate) and [`replaysOnErrorSampleRate`](https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options.md#replaysOnErrorSampleRate)
* User Feedback: via [`feedbackIntegration()`](https://docs.sentry.io/platforms/javascript/guides/nextjs/user-feedback/configuration.md). The wizard doesn't add this integration, so add it to `instrumentation-client.ts` yourself.

Don't need a feature? Remove its integration and options from the snippets.

**\[Client] instrumentation-client.ts**

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

Sentry.init({
  dsn: "https://<key>@o<orgId>.ingest.sentry.io/<projectId>",

  // Enables Tracing.
  // Capture 100% in dev, 10% in production
  // Adjust based on your traffic volume
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
  integrations: [
    // enables Session Replay
    Sentry.replayIntegration(),
    // enables User Feedback
    Sentry.feedbackIntegration({
      // Additional integration configuration goes in here
      colorScheme: "system",
    }),
  ],

  // Capture replays for 10% of all sessions,
  // plus for 100% of sessions with an error
  // Requires Sentry.replayIntegration()
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;
```

**\[Server] sentry.server.config.ts**

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

Sentry.init({
  dsn: "https://<key>@o<orgId>.ingest.sentry.io/<projectId>",

  // Enables Tracing.
  // Capture 100% in dev, 10% in production
  // Adjust based on your traffic volume
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
});
```

**\[Edge] sentry.edge.config.ts**

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

Sentry.init({
  dsn: "https://<key>@o<orgId>.ingest.sentry.io/<projectId>",

  // Enables Tracing.
  // Capture 100% in dev, 10% in production
  // Adjust based on your traffic volume
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
});
```

##### Adjust sample rates for production

The example above samples 100% of traces in development and 10% in production. Monitor your [usage stats](https://sentry.io/orgredirect/organizations/:orgslug/settings/stats/?dataCategory=spans) and adjust `tracesSampleRate` based on your traffic volume. Learn more about [sampling configuration](https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/sampling.md).

### [Register Server-Side SDK](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#register-server-side-sdk)

Create a [Next.js Instrumentation file](https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation) named `instrumentation.ts` next to your `app` directory (in your project root, or in `src` if you use `src/app`). Next.js production builds don't pick it up from other folders. This file imports your server and edge configurations and exports `onRequestError` to capture server-side errors.

The `onRequestError` hook requires `@sentry/nextjs` version `8.28.0` or higher and Next.js 15.

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

// Capture errors from Server Components, middleware, and proxies
export const onRequestError = Sentry.captureRequestError;
```

### [Capture React Render Errors](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#capture-react-render-errors)

Create `app/global-error.tsx` to capture errors that occur anywhere in your App Router application.

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

*Other available variations of the above snippet: jsx*

### [Server Actions](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#server-actions)

Wrap your Server Actions with `Sentry.withServerActionInstrumentation()`.

```typescript
"use server";
import * as Sentry from "@sentry/nextjs";
import { headers } from "next/headers";

export async function submitForm(formData: FormData) {
  return Sentry.withServerActionInstrumentation(
    "submitForm", // Action name for Sentry
    {
      headers: await headers(), // Connect client and server traces
      formData, // Attach form data to events
      recordResponse: true, // Include response data
    },
    async () => {
      // Your server action logic
      const result = await processForm(formData);
      return { success: true, data: result };
    },
  );
}
```

### [Add Readable Stack Traces With Source Maps](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#add-readable-stack-traces-with-source-maps)

Add the `authToken` option to your `next.config.ts` to enable readable stack traces. Set the `SENTRY_AUTH_TOKEN` environment variable in your CI/CD.

##### Important

Keep your auth token secret and out of version control.

```typescript
export default withSentryConfig(nextConfig, {
  org: "<your-org-slug>",
  project: "<your-project-slug>",

  // Pass the auth token
  authToken: process.env.SENTRY_AUTH_TOKEN,

  // Upload a larger set of source maps for prettier stack traces
  widenClientFileUpload: true,
});
```

*Other available variations of the above snippet: sh*

### [Avoid Ad Blockers With Tunneling](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#avoid-ad-blockers-with-tunneling)

Prevent ad blockers from blocking Sentry events by routing them through your Next.js server.

This increases server load. Consider the trade-off for your application.

Set `tunnel: true` in your browser `Sentry.init`, and add `serveTunnelIntegration` to your server `Sentry.init`:

```javascript
Sentry.init({
  dsn: "https://<key>@o<orgId>.ingest.sentry.io/<projectId>",
  tunnel: true,
});
```

```javascript
Sentry.init({
  dsn: "https://<key>@o<orgId>.ingest.sentry.io/<projectId>",
  integrations: [Sentry.serveTunnelIntegration()],
});
```

*Other available variations of the above snippet: Edge*

Add the integration to both files.

Learn more in [Tunneling](https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/tunneling.md).

### [Control the Data You Send to Sentry](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#control-the-data-you-send-to-sentry)

By default, the SDK sends user identity data (IP address, ID, and similar) and other data like HTTP bodies and URL query parameters. This will give you rich debugging context.

The SDK always filters sensitive values whose keys match a built-in denylist, such as `auth` or `password`, and sends `[Filtered]` instead.

To send less data, turn off the categories you don't need in the `dataCollection` option. For the full list of categories and their defaults, [see the `dataCollection` options](https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options.md#dataCollection).

```javascript
Sentry.init({
  dsn: "https://<key>@o<orgId>.ingest.sentry.io/<projectId>",
  dataCollection: {
    userInfo: false,
    // other categories
  },
});
```

## [Send Logs](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#send-logs)

Use `Sentry.logger` to send logs at different levels, such as `info`, `warn`, or `error`. You can pass any attributes you want and search or filter by them later. See [Set Up Logs](https://docs.sentry.io/platforms/javascript/guides/nextjs/logs.md) for all available logging methods and the syntax for formatting messages.

```javascript
Sentry.logger.info("User example action completed");

Sentry.logger.warn("Slow operation detected", {
  operation: "data_fetch",
  duration: 3500,
});

Sentry.logger.error("Validation failed", {
  form_field: "email",
  reason: "Invalid email",
});
```

If you're already logging with another library, use an integration to capture those logs as Sentry Logs automatically:

* [`consoleLoggingIntegration`](https://docs.sentry.io/platforms/javascript/guides/nextjs/logs.md#console) for `console` calls
* [Consola](https://docs.sentry.io/platforms/javascript/guides/nextjs/logs.md#consola)
* [Pino](https://docs.sentry.io/platforms/javascript/guides/nextjs/logs.md#pino)
* [Winston](https://docs.sentry.io/platforms/javascript/guides/nextjs/logs.md#winston)

## [Send Application Metrics NEW](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#send-application-metrics-)

Use `Sentry.metrics` to send counters, gauges, and distributions from your app to Sentry. You can pass any attributes you want and search or filter by them later. See [Set Up Metrics](https://docs.sentry.io/platforms/javascript/guides/nextjs/metrics.md) for all available metric types and configuration options.

```javascript
Sentry.metrics.count("checkout.failed", 1);

Sentry.metrics.gauge("time_since_refresh", 4, { unit: "hour" });

Sentry.metrics.distribution("api_latency", 187, {
  unit: "millisecond",
  attributes: { endpoint: "/api/orders" },
});
```

In the Node.js runtime, [`nodeRuntimeMetricsIntegration`](https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/integrations/noderuntimemetrics.md) also collects runtime health metrics automatically.

## [Verify Your Setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md#verify-your-setup)

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

Add this button to any page and click it to trigger a test error.

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

##### 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.

## Hybrid Apps (App Router + Pages Router)

If your application uses both the App Router and Pages Router:

1. Follow this guide for App Router components
2. Add a `pages/_error.tsx` file for Pages Router error handling (see [Pages Router Setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.md))
3. Both routers share the same Sentry configuration files

The Sentry SDK automatically detects which router is being used and applies the appropriate instrumentation.

## Next Steps

At this point, you should have integrated Sentry into your Next.js application. Here's what to explore next:

* Explore [practical guides](https://docs.sentry.io/get-started/guides.md) on what to monitor, log, track, and investigate after setup
* [Agent Tracing](https://docs.sentry.io/platforms/javascript/guides/nextjs/agent-tracing.md) - Monitor agents built with Vercel AI SDK, LangChain, and more
* [Connect GitHub + Seer](https://docs.sentry.io/integrations/source-code-mgmt/github.md#installing-github) - Enable AI-powered [root cause analysis](https://docs.sentry.io/product/ai-in-sentry/seer.md) by connecting your GitHub repository

Are you having problems setting up the SDK?

* Try the [installation wizard](https://docs.sentry.io/platforms/javascript/guides/nextjs.md) for automatic setup
* [Get support](https://www.sentry.help/en/)

## Pages in this section

- [Cloudflare](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/cloudflare.md)
- [Bun](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/bun.md)
- [Deno](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/deno.md)
- [Pages Router Setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.md)
- [Webpack Setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/webpack-setup.md)
