Pages Router Setup

Manual setup for Next.js applications using the Pages Router.

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

You need:

Choose the features you want to configure:

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

Copied
npm install @sentry/nextjs --save

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

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

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

export default withSentryConfig(nextConfig, {
  org: "___ORG_SLUG___",
  project: "___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,
    },
  },
});

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

  • sentry.client.config.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)
sentry.client.config.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

  // Capture 100% in dev, 10% in production
  // Adjust based on your traffic volume
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
  // ___PRODUCT_OPTION_END___ performance
    // ___PRODUCT_OPTION_START___ session-replay
    Sentry.replayIntegration(),
    // ___PRODUCT_OPTION_END___ session-replay
  // ___PRODUCT_OPTION_START___ session-replay

  // Capture Replay for 10% of all sessions,
  // plus for 100% of sessions with an error
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  // ___PRODUCT_OPTION_END___ session-replay
  // ___PRODUCT_OPTION_START___ logs

  // Enable logs to be sent to Sentry
  enableLogs: true,
  // ___PRODUCT_OPTION_END___ logs
});

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.

_error.tsx
Copied
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;

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.

next.config.ts
Copied
export default withSentryConfig(nextConfig, {
  org: "___ORG_SLUG___",
  project: "___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,
});

Test your error monitoring setup by throwing an error and viewing it in Sentry.

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

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

Open Issues in Sentry to see your test error. Learn more about capturing errors.

Based on the features you selected above, verify each one is working correctly.

Session Replay captures video-like reproductions of user sessions. It's configured with replayIntegration() in your client config.

Verify: Trigger an error or navigate your app, then check Replays in Sentry.

sentry.client.config.ts
Copied
Sentry.init({
  dsn: "___PUBLIC_DSN___",

  integrations: [Sentry.replayIntegration()],

  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

Tracing is configured with tracesSampleRate in your SDK init files. Next.js routes and API calls are automatically instrumented.

Verify: Navigate to any page, then check Traces in Sentry.

sentry.server.config.ts
Copied
Sentry.init({
  dsn: "___PUBLIC_DSN___",

  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
});

Logs are enabled with enableLogs: true in your SDK config. Use the Sentry logger to send structured logs.

Verify: Add a log statement, trigger it, then check Logs in Sentry.

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

Sentry.logger.info("User action", { userId: "123" });
Sentry.logger.warn("Warning message");
Sentry.logger.error("Error occurred");

Automatically create Cron Monitors in Sentry for your Vercel cron jobs.

Add the automaticVercelMonitors option to your next.config.ts.

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

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

Hybrid Apps (App Router + Pages Router)

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

  1. Follow the App Router Setup 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

Next Steps

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