Sentry Nextjs Sdk
Full Sentry SDK setup for Next.js. Use when asked to "add Sentry to Next.js", "install @sentry/nextjs", or configure error monitoring, tracing, session replay,…
Install
Quick install
npx skills add https://github.com/getsentry/sentry-agent-skills/tree/HEAD/skills/sentry-nextjs-sdknpx skills add getsentry/sentry-agent-skills --skill sentry-nextjs-sdk --agent claude-codenpx skills add getsentry/sentry-agent-skills --skill sentry-nextjs-sdk --agent cursornpx skills add getsentry/sentry-agent-skills --skill sentry-nextjs-sdk --agent codexnpx skills add getsentry/sentry-agent-skills --skill sentry-nextjs-sdk --agent opencodenpx skills add getsentry/sentry-agent-skills --skill sentry-nextjs-sdk --agent github-copilotnpx skills add getsentry/sentry-agent-skills --skill sentry-nextjs-sdk --agent windsurfMore install options
Shorthand — useful for multi-skill repos:
npx skills add getsentry/sentry-agent-skills --skill sentry-nextjs-sdkManual — clone the repo and drop the folder into your agent's skills directory:
git clone https://github.com/getsentry/sentry-agent-skills.gitcp -r sentry-agent-skills/skills/sentry-nextjs-sdk ~/.claude/skills/sentry-nextjs-sdk
Full Sentry SDK setup for Next.js. Use when asked to "add Sentry to Next.js", "install @sentry/nextjs", or configure error monitoring, tracing, session replay,…
sentry-nextjs-sdkby sentry
Full Sentry SDK setup for Next.js. Use when asked to "add Sentry to Next.js", "install @sentry/nextjs", or configure error monitoring, tracing, session replay,…npx skills add https://github.com/getsentry/sentry-agent-skills --skill sentry-nextjs-sdkDownload ZIPGitHub
Sentry Next.js SDK
Opinionated wizard that scans your Next.js project and guides you through complete Sentry setup across all three runtimes: browser, Node.js server, and Edge.
Invoke This Skill When
- User asks to "add Sentry to Next.js" or "set up Sentry" in a Next.js app
- User wants to install or configure
@sentry/nextjs
- User wants error monitoring, tracing, session replay, logging, or profiling for Next.js
- User asks about
instrumentation.ts,withSentryConfig(), orglobal-error.tsx
- User wants to capture server actions, server component errors, or edge runtime errors
Note: SDK versions and APIs below reflect current Sentry docs at time of writing (@sentry/nextjs ≥8.28.0).
Always verify against docs.sentry.io/platforms/javascript/guides/nextjs/ before implementing.
Phase 1: Detect
Run these commands to understand the project before making any recommendations:
`# Detect Next.js version and existing Sentry
cat package.json | grep -E '"next"|"@sentry/'
# Detect router type (App Router vs Pages Router)
ls src/app app src/pages pages 2>/dev/null
# Check for existing Sentry config files
ls instrumentation.ts instrumentation-client.ts sentry.server.config.ts sentry.edge.config.ts 2>/dev/null
ls src/instrumentation.ts src/instrumentation-client.ts 2>/dev/null
# Check next.config
ls next.config.ts next.config.js next.config.mjs 2>/dev/null
# Check for existing error boundaries
find . -name "global-error.tsx" -o -name "_error.tsx" 2>/dev/null | grep -v node_modules
# Check build tool
cat package.json | grep -E '"turbopack"|"webpack"'
# Check for logging libraries
cat package.json | grep -E '"pino"|"winston"|"bunyan"'
# Check for companion backend
ls ../backend ../server ../api 2>/dev/null
cat ../go.mod ../requirements.txt ../Gemfile 2>/dev/null | head -3
`
What to determine:
QuestionImpactNext.js version?13+ required; 15+ needed for Turbopack supportApp Router or Pages Router?Determines error boundary files needed (global-error.tsx vs _error.tsx)@sentry/nextjs already present?Skip install, go to feature configExisting instrumentation.ts?Merge Sentry into it rather than replaceTurbopack in use?Tree-shaking in withSentryConfig is webpack-onlyLogging library detected?Recommend Sentry Logs integrationBackend directory found?Trigger Phase 4 cross-link suggestion
Phase 2: Recommend
Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage):
- ✅ Error Monitoring — always; captures server errors, client errors, server actions, and unhandled promise rejections
- ✅ Tracing — server-side request tracing + client-side navigation spans across all runtimes
- ✅ Session Replay — recommended for user-facing apps; records sessions around errors
Optional (enhanced observability):
⚡ Logging — structured logs via Sentry.logger.; recommend when pino/winston or log search is needed
- ⚡ Profiling — continuous profiling; requires
Document-Policy: js-profilingheader
- ⚡ AI Monitoring — OpenAI, Vercel AI SDK, Anthropic; recommend when AI/LLM calls detected
- ⚡ Crons — detect missed/failed scheduled jobs; recommend when cron patterns detected
⚡ Metrics — custom metrics via Sentry.metrics.; recommend when custom KPIs or business metrics needed
Recommendation logic:
FeatureRecommend when...Error MonitoringAlways — non-negotiable baselineTracingAlways for Next.js — server route tracing + client navigation are high-valueSession ReplayUser-facing app, login flows, or checkout pagesLoggingApp uses structured logging or needs log-to-trace correlationProfilingPerformance-critical app; client sets Document-Policy: js-profilingAI MonitoringApp makes OpenAI, Vercel AI SDK, or Anthropic callsCronsApp has Vercel Cron jobs, scheduled API routes, or node-cron usageMetricsApp needs custom counters, gauges, or histograms via Sentry.metrics.*
Propose: "I recommend setting up Error Monitoring + Tracing + Session Replay. Want me to also add Logging or Profiling?"
Phase 3: Guide
Option 1: Wizard (Recommended)
`npx @sentry/wizard@latest -i nextjs
`
The wizard walks you through login, org/project selection, and auth token setup interactively — no manual token creation needed. It then installs the SDK, creates all necessary config files (instrumentation-client.ts, sentry.server.config.ts, sentry.edge.config.ts, instrumentation.ts), wraps next.config.ts with withSentryConfig(), configures source map upload, and adds a /sentry-example-page for verification.
Skip to Verification after running the wizard.
Option 2: Manual Setup
Install
`npm install @sentry/nextjs --save
`
Create instrumentation-client.ts — Browser / Client Runtime
Older docs used sentry.client.config.ts — the current pattern is instrumentation-client.ts.
`import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN ?? "___PUBLIC_DSN___",
sendDefaultPii: true,
// 100% in dev, 10% in production
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
// Session Replay: 10% of all sessions, 100% of sessions with errors
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
enableLogs: true,
integrations: [
Sentry.replayIntegration(),
// Optional: user feedback widget
// Sentry.feedbackIntegration({ colorScheme: "system" }),
],
});
// Hook into App Router navigation transitions (App Router only)
export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;
`
Create sentry.server.config.ts — Node.js Server Runtime
`import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
// Attach local variable values to stack frames
includeLocalVariables: true,
enableLogs: true,
});
`
Create sentry.edge.config.ts — Edge Runtime
`import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
enableLogs: true,
});
`
Create instrumentation.ts — Server-Side Registration Hook
Requires experimental.instrumentationHook: true in next.config for Next.js < 14.0.4. It's stable in 14.0.4+.
`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");
}
}
// Automatically captures all unhandled server-side request errors
// Requires @sentry/nextjs >= 8.28.0
export const onRequestError = Sentry.captureRequestError;
`
Runtime dispatch:
NEXT_RUNTIMEConfig file loaded"nodejs"sentry.server.config.ts"edge"sentry.edge.config.ts(client bundle)instrumentation-client.ts (Next.js handles this directly)
App Router: Create app/global-error.tsx
This catches errors in the root layout and React render errors:
`"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 statusCode={0} />
</body>
</html>
);
}
`
Pages Router: Update pages/_error.tsx
`import * as Sentry from "@sentry/nextjs";
import type { NextPageContext } from "next";
import NextErrorComponent from "next/error";
type ErrorProps = { statusCode: number };
export default function CustomError({ statusCode }: ErrorProps) {
return <NextErrorComponent statusCode={statusCode} />;
}
CustomError.getInitialProps = async (ctx: NextPageContext) => {
await Sentry.captureUnderscoreErrorException(ctx);
return NextErrorComponent.getInitialProps(ctx);
};
`
Wrap next.config.ts with withSentryConfig()
`import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs";
const nextConfig: NextConfig = {
// your existing Next.js config
};
export default withSentryConfig(nextConfig, {
org: "___ORG_SLUG___",
project: "___PROJECT_SLUG___",
// Source map upload auth token (see Source Maps section below)
authToken: process.env.SENTRY_AUTH_TOKEN,
// Upload wider set of client source files for better stack trace resolution
widenClientFileUpload: true,
// Create a proxy API route to bypass ad-blockers
tunnelRoute: "/monitoring",
// Suppress non-CI output
silent: !process.env.CI,
});
`
Exclude Tunnel Route from Middleware
If you have middleware.ts, exclude the tunnel path from auth or redirect logic:
`// middleware.ts
export const config = {
matcher: [
// Exclude monitoring route, Next.js internals, and static files
"/((?!monitoring|_next/static|_next/image|favicon.ico).*)",
],
};
`
Source Maps Setup
Source maps make production stack traces readable — without them, you see minified code. This is non-negotiable for production apps.
Step 1: Generate a Sentry auth token
Go to sentry.io/settings/auth-tokens/ and create a token with project:releases and org:read scopes.
Step 2: Set environment variables
`# .env.sentry-build-plugin (gitignore this file)
SENTRY_AUTH_TOKEN=sntrys_eyJ...
`
Or set in CI secrets:
`SENTRY_AUTH_TOKEN=sntrys_eyJ...
SENTRY_ORG=my-org # optional if set in next.config
SENTRY_PROJECT=my-project # optional if set in next.config
`
Step 3: Add to .gitignore
`.env.sentry-build-plugin
`
Step 4: Verify authToken is wired in next.config.ts
`withSentryConfig(nextConfig, {
org: "my-org",
project: "my-project",
authToken: process.env.SENTRY_AUTH_TOKEN, // reads from .env.sentry-build-plugin or CI env
widenClientFileUpload: true,
});
`
Source maps are uploaded automatically on every next build.
For Each Agreed Feature
Load the corresponding reference file and follow its steps:
FeatureReference fileLoad when...Error Monitoringreferences/error-monitoring.mdAlways (baseline) — App Router error boundaries, Pages Router _error.tsx, server action wrappingTracingreferences/tracing.mdServer-side request tracing, client navigation, distributed tracing, tracePropagationTargetsSession Replayreferences/session-replay.mdUser-facing app; privacy masking, canvas recording, network captureLoggingreferences/logging.mdStructured logs, Sentry.logger.*, log-to-trace correlationProfilingreferences/profiling.mdContinuous profiling, Document-Policy header, nodeProfilingIntegrationAI Monitoringreferences/ai-monitoring.mdApp uses OpenAI, Vercel AI SDK, or AnthropicCronsreferences/crons.mdVercel Cron, scheduled API routes, node-cron
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
Verification
After wizard or manual setup, verify Sentry is working:
`// Add temporarily to a server action or API route, then remove
import * as Sentry from "@sentry/nextjs";
throw new Error("Sentry test error — delete me");
// or
Sentry.captureException(new Error("Sentry test error — delete me"));
`
Then check your Sentry Issues dashboard — the error should appear within ~30 seconds.
Verification checklist:
CheckHowClient errors capturedThrow in a client component, verify in SentryServer errors capturedThrow in a server action or API routeEdge errors capturedThrow in middleware or edge route handlerSource maps workingCheck stack trace shows readable file namesSession Replay workingCheck Replays tab in Sentry dashboard
Config Reference
Sentry.init() Options
OptionTypeDefaultNotesdsnstring—Required. Use NEXT_PUBLIC_SENTRY_DSN for client, SENTRY_DSN for servertracesSampleRatenumber—0–1; 1.0 in dev, 0.1 in prod recommendedreplaysSessionSampleRatenumber0.1Fraction of all sessions recordedreplaysOnErrorSampleRatenumber1.0Fraction of error sessions recordedsendDefaultPiibooleanfalseInclude IP, request headers in eventsincludeLocalVariablesbooleanfalseAttach local variable values to stack frames (server only)enableLogsbooleanfalseEnable Sentry Logs productenvironmentstringauto"production", "staging", etc.releasestringautoSet to commit SHA or version tagdebugbooleanfalseLog SDK activity to console
withSentryConfig() Options
OptionTypeNotesorgstringSentry organization slugprojectstringSentry project slugauthTokenstringSource map upload token (SENTRY_AUTH_TOKEN)widenClientFileUploadbooleanUpload more client files for better stack tracestunnelRoutestringAPI route path for ad-blocker bypass (e.g. "/monitoring")silentbooleanSuppress build output (!process.env.CI recommended)webpack.treeshake.*objectTree-shake SDK features (webpack only, not Turbopack)
Environment Variables
VariableRuntimePurposeNEXT_PUBLIC_SENTRY_DSNClientDSN for browser Sentry init (public)SENTRY_DSNServer / EdgeDSN for server/edge Sentry initSENTRY_AUTH_TOKENBuildSource map upload auth token (secret)SENTRY_ORGBuildOrg slug (alternative to org in config)SENTRY_PROJECTBuildProject slug (alternative to project in config)SENTRY_RELEASEServerRelease version string (auto-detected from git)NEXT_RUNTIMEServer / Edge"nodejs" or "edge" (set by Next.js internally)
Phase 4: Cross-Link
After completing Next.js setup, check for companion services:
`# Check for backend services in adjacent directories
ls ../backend ../server ../api ../services 2>/dev/null
# Check for backend language indicators
cat ../go.mod 2>/dev/null | head -3
cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -3
cat ../Gemfile 2>/dev/null | head -3
cat ../pom.xml ../build.gradle 2>/dev/null | head -3
`
If a backend is found, suggest the matching SDK skill:
Backend detectedSuggest skillGo (go.mod)sentry-go-sdkPython (requirements.txt, pyproject.toml)sentry-python-sdkRuby (Gemfile)sentry-ruby-sdkJava/Kotlin (pom.xml, build.gradle)See docs.sentry.io/platforms/java/Node.js (Express, Fastify, Hapi)@sentry/node — see docs.sentry.io/platforms/javascript/guides/express/
Connecting frontend and backend with the same DSN or linked projects enables distributed tracing — stack traces that span your browser, Next.js server, and backend API in a single trace view.
Troubleshooting
IssueCauseSolutionEvents not appearingDSN misconfigured or debug: false hiding errorsSet debug: true temporarily; check browser network tab for requests to sentry.ioStack traces show minified codeSource maps not uploadingCheck SENTRY_AUTH_TOKEN is set; run next build and look for "Source Maps" in build outputonRequestError not firingSDK version < 8.28.0Upgrade: npm install @sentry/nextjs@latestEdge runtime errors missingsentry.edge.config.ts not loadedVerify instrumentation.ts imports it when NEXT_RUNTIME === "edge"Tunnel route returns 404tunnelRoute set but Next.js route missingThe plugin creates it automatically; check you ran next build after adding tunnelRoutewithSentryConfig tree-shaking breaks buildTurbopack in useTree-shaking options only work with webpack; remove webpack.treeshake options when using Turbopackglobal-error.tsx not catching errorsMissing "use client" directiveAdd "use client" as the very first line of global-error.tsxSession Replay not recordingreplayIntegration() missing from client initAdd Sentry.replayIntegration() to integrations in instrumentation-client.ts
More skills from sentry
sentry-cocoa-sdkby sentryFull Sentry SDK setup for Apple platforms (iOS, macOS, tvOS, watchOS, visionOS). Use when asked to "add Sentry to iOS", "add Sentry to Swift", "install…sentry-create-alertby sentryCreate Sentry alerts using the workflow engine API. Use when asked to create alerts, set up notifications, configure issue priority alerts, or build workflow…sentry-dotnet-sdkby sentryFull Sentry SDK setup for .NET. Use when asked to "add Sentry to .NET", "install Sentry for C#", or configure error monitoring, tracing, profiling, logging, or…sentry-fix-issuesby sentryFind and fix issues from Sentry using MCP. Use when asked to fix Sentry errors, debug production issues, investigate exceptions, or resolve bugs reported in…sentry-go-sdkby sentryFull Sentry SDK setup for Go. Use when asked to "add Sentry to Go", "install sentry-go", "setup Sentry in Go", or configure error monitoring, tracing, logging,…sentry-ios-swift-setupby sentrySetup Sentry in iOS/Swift apps. Use when asked to add Sentry to iOS, install sentry-cocoa SDK, or configure error monitoring for iOS applications using Swift…sentry-nextjs-sdkby sentryFull Sentry SDK setup for Next.js. Use when asked to "add Sentry to Next.js", "install @sentry/nextjs", or configure error monitoring, tracing, session replay,…sentry-otel-exporter-setupby sentryConfigure the OpenTelemetry Collector with Sentry Exporter for multi-project routing and automatic project creation. Use when setting up OTel with Sentry,…---
Source: https://github.com/getsentry/sentry-agent-skills/tree/HEAD/skills/sentry-nextjs-sdk
Author: sentry
Discovered via: mcpservers.org
SKILL.md source
---
name: sentry-nextjs-sdk
description: Full Sentry SDK setup for Next.js. Use when asked to "add Sentry to Next.js", "install @sentry/nextjs", or configure error monitoring, tracing, session replay,…
---
# sentry-nextjs-sdk
Full Sentry SDK setup for Next.js. Use when asked to "add Sentry to Next.js", "install @sentry/nextjs", or configure error monitoring, tracing, session replay,…
# sentry-nextjs-sdkby sentry
Full Sentry SDK setup for Next.js. Use when asked to "add Sentry to Next.js", "install @sentry/nextjs", or configure error monitoring, tracing, session replay,…
`npx skills add https://github.com/getsentry/sentry-agent-skills --skill sentry-nextjs-sdk`Download ZIPGitHub
## Sentry Next.js SDK
Opinionated wizard that scans your Next.js project and guides you through complete Sentry setup across all three runtimes: browser, Node.js server, and Edge.
## Invoke This Skill When
* User asks to "add Sentry to Next.js" or "set up Sentry" in a Next.js app
* User wants to install or configure `@sentry/nextjs`
* User wants error monitoring, tracing, session replay, logging, or profiling for Next.js
* User asks about `instrumentation.ts`, `withSentryConfig()`, or `global-error.tsx`
* User wants to capture server actions, server component errors, or edge runtime errors
Note: SDK versions and APIs below reflect current Sentry docs at time of writing (`@sentry/nextjs` ≥8.28.0).
Always verify against docs.sentry.io/platforms/javascript/guides/nextjs/ before implementing.
## Phase 1: Detect
Run these commands to understand the project before making any recommendations:
```
`# Detect Next.js version and existing Sentry
cat package.json | grep -E '"next"|"@sentry/'
# Detect router type (App Router vs Pages Router)
ls src/app app src/pages pages 2>/dev/null
# Check for existing Sentry config files
ls instrumentation.ts instrumentation-client.ts sentry.server.config.ts sentry.edge.config.ts 2>/dev/null
ls src/instrumentation.ts src/instrumentation-client.ts 2>/dev/null
# Check next.config
ls next.config.ts next.config.js next.config.mjs 2>/dev/null
# Check for existing error boundaries
find . -name "global-error.tsx" -o -name "_error.tsx" 2>/dev/null | grep -v node_modules
# Check build tool
cat package.json | grep -E '"turbopack"|"webpack"'
# Check for logging libraries
cat package.json | grep -E '"pino"|"winston"|"bunyan"'
# Check for companion backend
ls ../backend ../server ../api 2>/dev/null
cat ../go.mod ../requirements.txt ../Gemfile 2>/dev/null | head -3
`
```
What to determine:
QuestionImpactNext.js version?13+ required; 15+ needed for Turbopack supportApp Router or Pages Router?Determines error boundary files needed (`global-error.tsx` vs `_error.tsx`)`@sentry/nextjs` already present?Skip install, go to feature configExisting `instrumentation.ts`?Merge Sentry into it rather than replaceTurbopack in use?Tree-shaking in `withSentryConfig` is webpack-onlyLogging library detected?Recommend Sentry Logs integrationBackend directory found?Trigger Phase 4 cross-link suggestion
## Phase 2: Recommend
Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage):
* ✅ Error Monitoring — always; captures server errors, client errors, server actions, and unhandled promise rejections
* ✅ Tracing — server-side request tracing + client-side navigation spans across all runtimes
* ✅ Session Replay — recommended for user-facing apps; records sessions around errors
Optional (enhanced observability):
* ⚡ Logging — structured logs via `Sentry.logger.*`; recommend when `pino`/`winston` or log search is needed
* ⚡ Profiling — continuous profiling; requires `Document-Policy: js-profiling` header
* ⚡ AI Monitoring — OpenAI, Vercel AI SDK, Anthropic; recommend when AI/LLM calls detected
* ⚡ Crons — detect missed/failed scheduled jobs; recommend when cron patterns detected
* ⚡ Metrics — custom metrics via `Sentry.metrics.*`; recommend when custom KPIs or business metrics needed
Recommendation logic:
FeatureRecommend when...Error MonitoringAlways — non-negotiable baselineTracingAlways for Next.js — server route tracing + client navigation are high-valueSession ReplayUser-facing app, login flows, or checkout pagesLoggingApp uses structured logging or needs log-to-trace correlationProfilingPerformance-critical app; client sets `Document-Policy: js-profiling`AI MonitoringApp makes OpenAI, Vercel AI SDK, or Anthropic callsCronsApp has Vercel Cron jobs, scheduled API routes, or `node-cron` usageMetricsApp needs custom counters, gauges, or histograms via `Sentry.metrics.*`
Propose: "I recommend setting up Error Monitoring + Tracing + Session Replay. Want me to also add Logging or Profiling?"
## Phase 3: Guide
### Option 1: Wizard (Recommended)
```
`npx @sentry/wizard@latest -i nextjs
`
```
The wizard walks you through login, org/project selection, and auth token setup interactively — no manual token creation needed. It then installs the SDK, creates all necessary config files (`instrumentation-client.ts`, `sentry.server.config.ts`, `sentry.edge.config.ts`, `instrumentation.ts`), wraps `next.config.ts` with `withSentryConfig()`, configures source map upload, and adds a `/sentry-example-page` for verification.
Skip to Verification after running the wizard.
### Option 2: Manual Setup
Install
```
`npm install @sentry/nextjs --save
`
```
Create `instrumentation-client.ts` — Browser / Client Runtime
Older docs used `sentry.client.config.ts` — the current pattern is `instrumentation-client.ts`.
```
`import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN ?? "___PUBLIC_DSN___",
sendDefaultPii: true,
// 100% in dev, 10% in production
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
// Session Replay: 10% of all sessions, 100% of sessions with errors
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
enableLogs: true,
integrations: [
Sentry.replayIntegration(),
// Optional: user feedback widget
// Sentry.feedbackIntegration({ colorScheme: "system" }),
],
});
// Hook into App Router navigation transitions (App Router only)
export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;
`
```
Create `sentry.server.config.ts` — Node.js Server Runtime
```
`import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
// Attach local variable values to stack frames
includeLocalVariables: true,
enableLogs: true,
});
`
```
Create `sentry.edge.config.ts` — Edge Runtime
```
`import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
enableLogs: true,
});
`
```
Create `instrumentation.ts` — Server-Side Registration Hook
Requires `experimental.instrumentationHook: true` in `next.config` for Next.js < 14.0.4. It's stable in 14.0.4+.
```
`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");
}
}
// Automatically captures all unhandled server-side request errors
// Requires @sentry/nextjs >= 8.28.0
export const onRequestError = Sentry.captureRequestError;
`
```
Runtime dispatch:
`NEXT_RUNTIME`Config file loaded`"nodejs"``sentry.server.config.ts``"edge"``sentry.edge.config.ts`(client bundle)`instrumentation-client.ts` (Next.js handles this directly)
App Router: Create `app/global-error.tsx`
This catches errors in the root layout and React render errors:
```
`"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 statusCode={0} />
</body>
</html>
);
}
`
```
Pages Router: Update `pages/_error.tsx`
```
`import * as Sentry from "@sentry/nextjs";
import type { NextPageContext } from "next";
import NextErrorComponent from "next/error";
type ErrorProps = { statusCode: number };
export default function CustomError({ statusCode }: ErrorProps) {
return <NextErrorComponent statusCode={statusCode} />;
}
CustomError.getInitialProps = async (ctx: NextPageContext) => {
await Sentry.captureUnderscoreErrorException(ctx);
return NextErrorComponent.getInitialProps(ctx);
};
`
```
Wrap `next.config.ts` with `withSentryConfig()`
```
`import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs";
const nextConfig: NextConfig = {
// your existing Next.js config
};
export default withSentryConfig(nextConfig, {
org: "___ORG_SLUG___",
project: "___PROJECT_SLUG___",
// Source map upload auth token (see Source Maps section below)
authToken: process.env.SENTRY_AUTH_TOKEN,
// Upload wider set of client source files for better stack trace resolution
widenClientFileUpload: true,
// Create a proxy API route to bypass ad-blockers
tunnelRoute: "/monitoring",
// Suppress non-CI output
silent: !process.env.CI,
});
`
```
Exclude Tunnel Route from Middleware
If you have `middleware.ts`, exclude the tunnel path from auth or redirect logic:
```
`// middleware.ts
export const config = {
matcher: [
// Exclude monitoring route, Next.js internals, and static files
"/((?!monitoring|_next/static|_next/image|favicon.ico).*)",
],
};
`
```
### Source Maps Setup
Source maps make production stack traces readable — without them, you see minified code. This is non-negotiable for production apps.
Step 1: Generate a Sentry auth token
Go to sentry.io/settings/auth-tokens/ and create a token with `project:releases` and `org:read` scopes.
Step 2: Set environment variables
```
`# .env.sentry-build-plugin (gitignore this file)
SENTRY_AUTH_TOKEN=sntrys_eyJ...
`
```
Or set in CI secrets:
```
`SENTRY_AUTH_TOKEN=sntrys_eyJ...
SENTRY_ORG=my-org # optional if set in next.config
SENTRY_PROJECT=my-project # optional if set in next.config
`
```
Step 3: Add to `.gitignore`
```
`.env.sentry-build-plugin
`
```
Step 4: Verify `authToken` is wired in `next.config.ts`
```
`withSentryConfig(nextConfig, {
org: "my-org",
project: "my-project",
authToken: process.env.SENTRY_AUTH_TOKEN, // reads from .env.sentry-build-plugin or CI env
widenClientFileUpload: true,
});
`
```
Source maps are uploaded automatically on every `next build`.
### For Each Agreed Feature
Load the corresponding reference file and follow its steps:
FeatureReference fileLoad when...Error Monitoring`references/error-monitoring.md`Always (baseline) — App Router error boundaries, Pages Router `_error.tsx`, server action wrappingTracing`references/tracing.md`Server-side request tracing, client navigation, distributed tracing, `tracePropagationTargets`Session Replay`references/session-replay.md`User-facing app; privacy masking, canvas recording, network captureLogging`references/logging.md`Structured logs, `Sentry.logger.*`, log-to-trace correlationProfiling`references/profiling.md`Continuous profiling, `Document-Policy` header, `nodeProfilingIntegration`AI Monitoring`references/ai-monitoring.md`App uses OpenAI, Vercel AI SDK, or AnthropicCrons`references/crons.md`Vercel Cron, scheduled API routes, `node-cron`
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
## Verification
After wizard or manual setup, verify Sentry is working:
```
`// Add temporarily to a server action or API route, then remove
import * as Sentry from "@sentry/nextjs";
throw new Error("Sentry test error — delete me");
// or
Sentry.captureException(new Error("Sentry test error — delete me"));
`
```
Then check your Sentry Issues dashboard — the error should appear within ~30 seconds.
Verification checklist:
CheckHowClient errors capturedThrow in a client component, verify in SentryServer errors capturedThrow in a server action or API routeEdge errors capturedThrow in middleware or edge route handlerSource maps workingCheck stack trace shows readable file namesSession Replay workingCheck Replays tab in Sentry dashboard
## Config Reference
### `Sentry.init()` Options
OptionTypeDefaultNotes`dsn``string`—Required. Use `NEXT_PUBLIC_SENTRY_DSN` for client, `SENTRY_DSN` for server`tracesSampleRate``number`—0–1; 1.0 in dev, 0.1 in prod recommended`replaysSessionSampleRate``number``0.1`Fraction of all sessions recorded`replaysOnErrorSampleRate``number``1.0`Fraction of error sessions recorded`sendDefaultPii``boolean``false`Include IP, request headers in events`includeLocalVariables``boolean``false`Attach local variable values to stack frames (server only)`enableLogs``boolean``false`Enable Sentry Logs product`environment``string`auto`"production"`, `"staging"`, etc.`release``string`autoSet to commit SHA or version tag`debug``boolean``false`Log SDK activity to console
### `withSentryConfig()` Options
OptionTypeNotes`org``string`Sentry organization slug`project``string`Sentry project slug`authToken``string`Source map upload token (`SENTRY_AUTH_TOKEN`)`widenClientFileUpload``boolean`Upload more client files for better stack traces`tunnelRoute``string`API route path for ad-blocker bypass (e.g. `"/monitoring"`)`silent``boolean`Suppress build output (`!process.env.CI` recommended)`webpack.treeshake.*``object`Tree-shake SDK features (webpack only, not Turbopack)
### Environment Variables
VariableRuntimePurpose`NEXT_PUBLIC_SENTRY_DSN`ClientDSN for browser Sentry init (public)`SENTRY_DSN`Server / EdgeDSN for server/edge Sentry init`SENTRY_AUTH_TOKEN`BuildSource map upload auth token (secret)`SENTRY_ORG`BuildOrg slug (alternative to `org` in config)`SENTRY_PROJECT`BuildProject slug (alternative to `project` in config)`SENTRY_RELEASE`ServerRelease version string (auto-detected from git)`NEXT_RUNTIME`Server / Edge`"nodejs"` or `"edge"` (set by Next.js internally)
## Phase 4: Cross-Link
After completing Next.js setup, check for companion services:
```
`# Check for backend services in adjacent directories
ls ../backend ../server ../api ../services 2>/dev/null
# Check for backend language indicators
cat ../go.mod 2>/dev/null | head -3
cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -3
cat ../Gemfile 2>/dev/null | head -3
cat ../pom.xml ../build.gradle 2>/dev/null | head -3
`
```
If a backend is found, suggest the matching SDK skill:
Backend detectedSuggest skillGo (`go.mod`)`sentry-go-sdk`Python (`requirements.txt`, `pyproject.toml`)`sentry-python-sdk`Ruby (`Gemfile`)`sentry-ruby-sdk`Java/Kotlin (`pom.xml`, `build.gradle`)See docs.sentry.io/platforms/java/Node.js (Express, Fastify, Hapi)`@sentry/node` — see docs.sentry.io/platforms/javascript/guides/express/
Connecting frontend and backend with the same DSN or linked projects enables distributed tracing — stack traces that span your browser, Next.js server, and backend API in a single trace view.
## Troubleshooting
IssueCauseSolutionEvents not appearingDSN misconfigured or `debug: false` hiding errorsSet `debug: true` temporarily; check browser network tab for requests to `sentry.io`Stack traces show minified codeSource maps not uploadingCheck `SENTRY_AUTH_TOKEN` is set; run `next build` and look for "Source Maps" in build output`onRequestError` not firingSDK version < 8.28.0Upgrade: `npm install @sentry/nextjs@latest`Edge runtime errors missing`sentry.edge.config.ts` not loadedVerify `instrumentation.ts` imports it when `NEXT_RUNTIME === "edge"`Tunnel route returns 404`tunnelRoute` set but Next.js route missingThe plugin creates it automatically; check you ran `next build` after adding `tunnelRoute``withSentryConfig` tree-shaking breaks buildTurbopack in useTree-shaking options only work with webpack; remove `webpack.treeshake` options when using Turbopack`global-error.tsx` not catching errorsMissing `"use client"` directiveAdd `"use client"` as the very first line of `global-error.tsx`Session Replay not recording`replayIntegration()` missing from client initAdd `Sentry.replayIntegration()` to `integrations` in `instrumentation-client.ts`
## More skills from sentry
sentry-cocoa-sdkby sentryFull Sentry SDK setup for Apple platforms (iOS, macOS, tvOS, watchOS, visionOS). Use when asked to "add Sentry to iOS", "add Sentry to Swift", "install…sentry-create-alertby sentryCreate Sentry alerts using the workflow engine API. Use when asked to create alerts, set up notifications, configure issue priority alerts, or build workflow…sentry-dotnet-sdkby sentryFull Sentry SDK setup for .NET. Use when asked to "add Sentry to .NET", "install Sentry for C#", or configure error monitoring, tracing, profiling, logging, or…sentry-fix-issuesby sentryFind and fix issues from Sentry using MCP. Use when asked to fix Sentry errors, debug production issues, investigate exceptions, or resolve bugs reported in…sentry-go-sdkby sentryFull Sentry SDK setup for Go. Use when asked to "add Sentry to Go", "install sentry-go", "setup Sentry in Go", or configure error monitoring, tracing, logging,…sentry-ios-swift-setupby sentrySetup Sentry in iOS/Swift apps. Use when asked to add Sentry to iOS, install sentry-cocoa SDK, or configure error monitoring for iOS applications using Swift…sentry-nextjs-sdkby sentryFull Sentry SDK setup for Next.js. Use when asked to "add Sentry to Next.js", "install @sentry/nextjs", or configure error monitoring, tracing, session replay,…sentry-otel-exporter-setupby sentryConfigure the OpenTelemetry Collector with Sentry Exporter for multi-project routing and automatic project creation. Use when setting up OTel with Sentry,…
---
**Source**: https://github.com/getsentry/sentry-agent-skills/tree/HEAD/skills/sentry-nextjs-sdk
**Author**: sentry
**Discovered via**: mcpservers.org
Related skills 6
find-skills
Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
appinsights-instrumentation
Guidance for instrumenting webapps with Azure Application Insights. Provides telemetry patterns, SDK setup, and configuration references. WHEN: how to instrument app, App Insights SDK, telemetry patterns, what is App Insights, Application Insights guidance, instrumentation examples, APM best practices.
azure-messaging
Troubleshoot and resolve issues with Azure Messaging SDKs for Event Hubs and Service Bus. Covers connection failures, authentication errors, message processing issues, and SDK configuration problems. WHEN: event hub SDK error, service bus SDK issue, messaging connection failure, AMQP error, event processor host issue, message lock lost, message lock expired, lock renewal, lock renewal batch, send timeout, receiver disconnected, SDK troubleshooting, azure messaging SDK, event hub consumer, ser...
azure-hosted-copilot-sdk
Build, deploy, and modify GitHub Copilot SDK apps on Azure. MANDATORY when codebase contains @github/copilot-sdk or CopilotClient in package.json. PREFER OVER azure-prepare when copilot-sdk markers detected. WHEN: copilot SDK, @github/copilot-sdk, copilot-powered app, build copilot app, prepare copilot app, add feature to copilot app, modify copilot app, BYOM, bring your own model, CopilotClient, createSession, sendAndWait, azd init copilot. DO NOT USE FOR: deploying already-prepared copilot-...
lark-event
Lark/Feishu real-time event listening / subscribing / consuming: stream events as NDJSON via `lark-cli event consume <EventKey>` (covers IM message receive, reactions, chat member changes, etc.). Use for Lark bots, real-time message processing, long-running subscribers, streaming webhook/push handlers. Supports `--max-events` / `--timeout` bounded runs and a stderr ready-marker contract — designed for AI agents running as subprocesses.
xget
Use when tasks involve Xget URL rewriting, registry/package/container/API acceleration, integrating Xget into Git, download tools, package managers, container builds, AI SDKs, CI/CD, deployment, self-hosting, or adapting commands and config from the live README `Use Cases` section into files, environments, shells, or base URLs.