---
title: "Pages Router Setup"
description: "Learn how to set up and configure Sentry in your Next.js application using the Pages Router and capture your first events in Sentry."
url: https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router/
last_updated: 2026-11-18T09:53:37.000Z
---

# Pages Router Setup for Next.js

For the fastest setup, we recommend using the [wizard installer](https://docs.sentry.io/platforms/javascript/guides/nextjs.md).

This guide covers manual setup for **Next.js applications using the Pages Router**. For other setups, see:

* [App Router Setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md) - For applications using the App Router (Next.js 15+)
* [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/pages-router.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/pages-router.md#install)

### [Install the Sentry SDK](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.md#install-the-sentry-sdk)

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/pages-router.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/pages-router.md#send-logs) and [#4](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.md#send-application-metrics-). This guide also enables **Tracing** and **Session Replay**.

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.
* [**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/pages-router.md#apply-instrumentation-to-your-app)

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

Pages Router applications typically use Webpack. The Webpack configuration includes auto-instrumentation options that automatically wrap your API routes and page data fetching methods.

```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,

  // Webpack-specific options for Pages Router
  webpack: {
    // Auto-instrument API routes and data fetching methods (default: true)
    autoInstrumentServerFunctions: true,

    // Auto-instrument middleware (default: true)
    autoInstrumentMiddleware: true,

    // Tree-shake Sentry logger statements to reduce bundle size
    treeshake: {
      removeDebugLogging: true,
    },
  },
});
```

*Other available variations of the above snippet: Turbopack*

### [Initialize Sentry SDKs](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.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 (if using edge routes)

##### Tip

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

##### Don't use sentry.client.config.ts

Older setups initialized the browser SDK in `sentry.client.config.ts`. That file is deprecated and is **ignored entirely by Turbopack builds**, which leaves your app with no browser SDK and no build error to tell you. Use `instrumentation-client.ts` instead.

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)

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>",

  // Capture 100% in dev, 10% in production
  // Adjust based on your traffic volume
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
  integrations: [Sentry.replayIntegration()],

  // Capture Replay for 10% of all sessions,
  // plus for 100% of sessions with an error
  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>",

  // 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>",

  // 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

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/pages-router.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 `pages` directory (in your project root, or in `src` if you use `src/pages`) to load it at server startup. Next.js production builds don't pick it up from other folders.

The `onRequestError` export is what captures server-side errors in the Pages Router, including errors thrown in API routes and `getServerSideProps`.

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 API routes, getServerSideProps, and middleware
export const onRequestError = Sentry.captureRequestError;
```

### [Capture Pages Router Errors](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.md#capture-pages-router-errors)

Create or update `pages/_error.tsx` to capture errors that occur during server-side rendering or in page components.

The `getInitialProps` method captures the error asynchronously, ensuring Sentry has time to send the error before serverless functions terminate.

```tsx
import * as Sentry from "@sentry/nextjs";
import type { NextPage } from "next";
import type { ErrorProps } from "next/error";
import Error from "next/error";

const CustomErrorComponent: NextPage<ErrorProps> = (props) => {
  return <Error statusCode={props.statusCode} />;
};

CustomErrorComponent.getInitialProps = async (contextData) => {
  // In case this is running in a serverless function, await this in order to give Sentry
  // time to send the error before the lambda exits
  await Sentry.captureUnderscoreErrorException(contextData);

  // This will contain the status code of the response
  return Error.getInitialProps(contextData);
};

export default CustomErrorComponent;
```

*Other available variations of the above snippet: jsx*

### [Add Readable Stack Traces With Source Maps](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.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*

### [Control the Data You Send to Sentry](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.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/pages-router.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/pages-router.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.

## [Vercel Cron Jobs (Optional)](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.md#vercel-cron-jobs-optional)

Automatically create [Cron Monitors](https://docs.sentry.io/product/monitors-and-alerts/monitors/crons.md) in Sentry for your [Vercel cron jobs](https://vercel.com/docs/cron-jobs).

### [Enable Automatic Cron Monitoring](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.md#enable-automatic-cron-monitoring)

There are two ways to do this, depending on how you build:

* `_experimental.vercelCronsMonitoring` creates check-ins from spans. It works with both Turbopack and Webpack, and with both routers. Prefer this one.
* `webpack.automaticVercelMonitors` wraps your route handlers at build time. It only works with Webpack and the Pages Router.

If you enable both, the SDK uses the span-based approach and logs a warning telling you to drop the other one.

**\[Span-based] next.config.ts**

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

export default withSentryConfig(nextConfig, {
  _experimental: {
    vercelCronsMonitoring: true,
  },
});
```

**\[Webpack] next.config.ts**

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

export default withSentryConfig(nextConfig, {
  webpack: {
    automaticVercelMonitors: true,
  },
});
```

## [Verify Your Setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/pages-router.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.

```tsx
export default function Home() {
  return (
    <button
      type="button"
      onClick={() => {
        throw new Error("Sentry Test Error");
      }}
    >
      Throw Test Error
    </button>
  );
}
```

## Hybrid Apps (App Router + Pages Router)

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

1. Follow the [App Router Setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup.md) for App Router components
2. Add the `pages/_error.tsx` file from this guide for Pages Router error handling
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

* 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)

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/)

---

Find other pages: [Sitemap](https://docs.sentry.io/sitemap.md) lists every page with a one-line summary, and [llms.txt](https://docs.sentry.io/llms.txt) gives an overview with guidance for agents.
