Pages Router Setup
Manual setup for Next.js applications using the Pages Router.
For the fastest setup, we recommend using the wizard installer.
This guide covers manual setup for Next.js applications using the Pages Router. For other setups, see:
- App Router Setup - For applications using the App Router (Next.js 15+)
- Webpack Setup - For applications not using Turbopack
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.
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.
Pages Router applications typically use Webpack. The Webpack configuration includes auto-instrumentation options that automatically wrap your API routes and page data fetching methods.
next.config.tsimport 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 initializationsentry.server.config.ts- Server-side SDK initializationsentry.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.
sentry.client.config.tsimport * 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
});
Adjust sample rates for production
Monitor your usage stats and adjust tracesSampleRate based on your traffic volume. Learn more about sampling configuration.
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.tsximport * 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.
Important
Keep your auth token secret and out of version control.
next.config.tsexport 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.tsxexport 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.tsSentry.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.tsSentry.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.
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.tsimport { 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:
- Follow the App Router Setup for App Router components
- Add the
pages/_error.tsxfile from this guide for Pages Router error handling - 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
- Logs Integrations - Connect popular logging libraries like Pino, Winston, and Bunyan
- Distributed Tracing - Trace requests across services and microservices
- AI Agent Monitoring - Monitor AI agents built with Vercel AI SDK, LangChain, and more
- Connect GitHub + Seer - Enable AI-powered root cause analysis
- Configuration Options - Explore extended SDK configuration
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").