sentry-nextjs-sdk by getsentry/sentry-for-ai
npx skills add https://github.com/getsentry/sentry-for-ai --skill sentry-nextjs-sdk一个具有明确导向的向导,它会扫描你的 Next.js 项目,并指导你在所有三个运行时(浏览器、Node.js 服务器和 Edge)中完成完整的 Sentry 设置。
@sentry/nextjsinstrumentation.ts、withSentryConfig() 或 global-error.tsx 的问题注意: 下文中的 SDK 版本和 API 反映了撰写本文时当前的 Sentry 文档 (
@sentry/nextjs≥8.28.0)。在实施前,请务必对照 进行验证。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
在提出任何建议之前,运行以下命令来了解项目:
# 检测 Next.js 版本和现有 Sentry
cat package.json | grep -E '"next"|"@sentry/'
# 检测路由类型(App Router 与 Pages Router)
ls src/app app src/pages pages 2>/dev/null
# 检查现有的 Sentry 配置文件
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
# 检查 next.config
ls next.config.ts next.config.js next.config.mjs 2>/dev/null
# 检查现有的错误边界
find . -name "global-error.tsx" -o -name "_error.tsx" 2>/dev/null | grep -v node_modules
# 检查构建工具
cat package.json | grep -E '"turbopack"|"webpack"'
# 检查日志记录库
cat package.json | grep -E '"pino"|"winston"|"bunyan"'
# 检查配套后端
ls ../backend ../server ../api 2>/dev/null
cat ../go.mod ../requirements.txt ../Gemfile 2>/dev/null | head -3
需要确定的内容:
| 问题 | 影响 |
|---|---|
| Next.js 版本? | 需要 13+;支持 Turbopack 需要 15+ |
| App Router 还是 Pages Router? | 决定所需的错误边界文件 (global-error.tsx vs _error.tsx) |
@sentry/nextjs 是否已存在? | 跳过安装,直接进入功能配置 |
现有的 instrumentation.ts? | 将 Sentry 合并到其中,而不是替换 |
| 是否使用 Turbopack? | withSentryConfig 中的摇树优化仅适用于 webpack |
| 检测到日志记录库? | 建议集成 Sentry Logs |
| 找到后端目录? | 触发阶段 4 的跨链接建议 |
根据你的发现提出具体建议。不要问开放式问题——直接提出方案:
推荐(核心覆盖范围):
可选(增强的可观测性):
Sentry.logger.* 实现结构化日志;当需要 pino/winston 或日志搜索时推荐Document-Policy: js-profiling 响应头Sentry.metrics.* 实现自定义指标;当需要自定义 KPI 或业务指标时推荐推荐逻辑:
| 功能 | 推荐时机... |
|---|---|
| 错误监控 | 始终 — 不可或缺的基线 |
| 追踪 | 对于 Next.js 始终推荐 — 服务器路由追踪 + 客户端导航具有高价值 |
| 会话回放 | 面向用户的应用、登录流程或结账页面 |
| 日志记录 | 应用使用结构化日志或需要日志与追踪关联 |
| 性能分析 | 性能关键型应用;客户端设置了 Document-Policy: js-profiling 响应头 |
| AI 监控 | 应用进行 OpenAI、Vercel AI SDK 或 Anthropic 调用 |
| Cron 任务 | 应用有 Vercel Cron 任务、定时 API 路由或使用 node-cron |
| 指标 | 应用需要通过 Sentry.metrics.* 实现自定义计数器、仪表盘或直方图 |
建议:"我建议设置错误监控 + 追踪 + 会话回放。还需要我添加日志记录或性能分析吗?"
你需要自己运行此命令 — 向导会打开浏览器进行登录,并需要代理无法处理的交互式输入。请复制粘贴到你的终端:
npx @sentry/wizard@latest -i nextjs它会处理登录、组织/项目选择、SDK 安装、配置文件 (
instrumentation-client.ts、sentry.server.config.ts、sentry.edge.config.ts、instrumentation.ts)、next.config.ts包装、源映射上传,并添加一个/sentry-example-page页面。完成后,请返回并跳转到验证部分。
如果用户跳过了向导,请继续下面的选项 2(手动设置)。
npm install @sentry/nextjs --save
instrumentation-client.ts — 浏览器 / 客户端运行时旧文档使用
sentry.client.config.ts— 当前模式是instrumentation-client.ts。
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN ?? "___PUBLIC_DSN___",
sendDefaultPii: true,
// 开发环境 100%,生产环境 10%
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
// 会话回放:所有会话的 10%,有错误的会话的 100%
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
enableLogs: true,
integrations: [
Sentry.replayIntegration(),
// 可选:用户反馈组件
// Sentry.feedbackIntegration({ colorScheme: "system" }),
],
});
// 挂钩到 App Router 导航转换(仅限 App Router)
export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;
sentry.server.config.ts — Node.js 服务器运行时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,
// 将局部变量值附加到堆栈帧
includeLocalVariables: true,
enableLogs: true,
});
sentry.edge.config.ts — Edge 运行时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,
});
instrumentation.ts — 服务器端注册钩子对于 Next.js < 14.0.4,需要在
next.config中设置experimental.instrumentationHook: true。在 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");
}
}
// 自动捕获所有未处理的服务器端请求错误
// 需要 @sentry/nextjs >= 8.28.0
export const onRequestError = Sentry.captureRequestError;
运行时分发:
NEXT_RUNTIME | 加载的配置文件 |
|---|---|
"nodejs" | sentry.server.config.ts |
"edge" | sentry.edge.config.ts |
| (客户端包) | instrumentation-client.ts (Next.js 直接处理) |
app/global-error.tsx这会捕获根布局中的错误和 React 渲染错误:
"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/_error.tsximport * 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);
};
withSentryConfig() 包装 next.config.tsimport type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs";
const nextConfig: NextConfig = {
// 你现有的 Next.js 配置
};
export default withSentryConfig(nextConfig, {
org: "___ORG_SLUG___",
project: "___PROJECT_SLUG___",
// 源映射上传身份验证令牌(见下文源映射部分)
authToken: process.env.SENTRY_AUTH_TOKEN,
// 上传更广泛的客户端源文件以获得更好的堆栈跟踪解析
widenClientFileUpload: true,
// 创建一个代理 API 路由以绕过广告拦截器
tunnelRoute: "/monitoring",
// 抑制非 CI 输出
silent: !process.env.CI,
});
如果你有 middleware.ts,请从身份验证或重定向逻辑中排除隧道路径:
// middleware.ts
export const config = {
matcher: [
// 排除监控路由、Next.js 内部文件和静态文件
"/((?!monitoring|_next/static|_next/image|favicon.ico).*)",
],
};
源映射使生产环境的堆栈跟踪可读——没有它们,你只能看到压缩后的代码。这对于生产应用是必不可少的。
步骤 1:生成 Sentry 身份验证令牌
前往 sentry.io/settings/auth-tokens/ 并创建一个具有 project:releases 和 org:read 范围的令牌。
步骤 2:设置环境变量
# .env.sentry-build-plugin (将此文件加入 gitignore)
SENTRY_AUTH_TOKEN=sntrys_eyJ...
或在 CI 密钥中设置:
SENTRY_AUTH_TOKEN=sntrys_eyJ...
SENTRY_ORG=my-org # 如果在 next.config 中设置了,则可选
SENTRY_PROJECT=my-project # 如果在 next.config 中设置了,则可选
步骤 3:添加到 .gitignore
.env.sentry-build-plugin
步骤 4:验证 authToken 已在 next.config.ts 中连接
withSentryConfig(nextConfig, {
org: "my-org",
project: "my-project",
authToken: process.env.SENTRY_AUTH_TOKEN, // 从 .env.sentry-build-plugin 或 CI 环境变量读取
widenClientFileUpload: true,
});
每次运行 next build 时,源映射会自动上传。
加载相应的参考文件并遵循其步骤:
| 功能 | 参考文件 | 加载时机... |
|---|---|---|
| 错误监控 | references/error-monitoring.md | 始终(基线)— App Router 错误边界、Pages Router _error.tsx、服务器操作包装 |
| 追踪 | references/tracing.md | 服务器端请求追踪、客户端导航、分布式追踪、tracePropagationTargets |
| 会话回放 | references/session-replay.md | 面向用户的应用;隐私屏蔽、画布录制、网络捕获 |
| 日志记录 | references/logging.md | 结构化日志、Sentry.logger.*、日志与追踪关联 |
| 性能分析 | references/profiling.md | 持续性能分析、Document-Policy 响应头、nodeProfilingIntegration |
| AI 监控 | references/ai-monitoring.md | 应用使用 OpenAI、Vercel AI SDK 或 Anthropic |
| Cron 任务 | references/crons.md | Vercel Cron、定时 API 路由、node-cron 使用 |
对于每个功能:阅读参考文件,严格按照其步骤操作,并在继续之前进行验证。
在向导或手动设置完成后,验证 Sentry 是否正常工作:
// 临时添加到服务器操作或 API 路由中,然后删除
import * as Sentry from "@sentry/nextjs";
throw new Error("Sentry 测试错误 — 请删除我");
// 或者
Sentry.captureException(new Error("Sentry 测试错误 — 请删除我"));
然后检查你的 Sentry Issues 仪表板 — 错误应在约 30 秒内出现。
验证清单:
| 检查项 | 方法 |
|---|---|
| 客户端错误捕获 | 在客户端组件中抛出错误,在 Sentry 中验证 |
| 服务器错误捕获 | 在服务器操作或 API 路由中抛出错误 |
| Edge 错误捕获 | 在中间件或 Edge 路由处理器中抛出错误 |
| 源映射正常工作 | 检查堆栈跟踪是否显示可读的文件名 |
| 会话回放正常工作 | 检查 Sentry 仪表板中的回放选项卡 |
Sentry.init() 选项| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
dsn | string | — | 必需。客户端使用 NEXT_PUBLIC_SENTRY_DSN,服务器使用 SENTRY_DSN |
tracesSampleRate | number | — | 0–1;开发环境推荐 1.0,生产环境推荐 0.1 |
replaysSessionSampleRate | number | 0.1 | 记录的所有会话的比例 |
replaysOnErrorSampleRate | number | 1.0 | 记录的有错误会话的比例 |
sendDefaultPii | boolean | false | 在事件中包含 IP、请求头 |
includeLocalVariables | boolean | false | 将局部变量值附加到堆栈帧(仅服务器端) |
enableLogs | boolean | false | 启用 Sentry Logs 产品 |
environment | string | auto | "production"、"staging" 等 |
release | string | auto | 设置为提交 SHA 或版本标签 |
debug | boolean | false | 将 SDK 活动记录到控制台 |
withSentryConfig() 选项| 选项 | 类型 | 说明 |
|---|---|---|
org | string | Sentry 组织 slug |
project | string | Sentry 项目 slug |
authToken | string | 源映射上传令牌 (SENTRY_AUTH_TOKEN) |
widenClientFileUpload | boolean | 上传更多客户端文件以获得更好的堆栈跟踪 |
tunnelRoute | string | 用于绕过广告拦截器的 API 路由路径(例如 "/monitoring") |
silent | boolean | 抑制构建输出(推荐使用 !process.env.CI) |
webpack.treeshake.* | object | 摇树优化 SDK 功能(仅限 webpack,不适用于 Turbopack) |
| 变量 | 运行时 | 用途 |
|---|---|---|
NEXT_PUBLIC_SENTRY_DSN | 客户端 | 浏览器 Sentry 初始化的 DSN(公开) |
SENTRY_DSN | 服务器 / Edge | 服务器/edge Sentry 初始化的 DSN |
SENTRY_AUTH_TOKEN | 构建 | 源映射上传身份验证令牌(密钥) |
SENTRY_ORG | 构建 | 组织 slug(替代配置中的 org) |
SENTRY_PROJECT | 构建 | 项目 slug(替代配置中的 project) |
SENTRY_RELEASE | 服务器 | 发布版本字符串(从 git 自动检测) |
NEXT_RUNTIME | 服务器 / Edge | "nodejs" 或 "edge"(由 Next.js 内部设置) |
完成 Next.js 设置后,检查配套服务:
# 检查相邻目录中的后端服务
ls ../backend ../server ../api ../services 2>/dev/null
# 检查后端语言指示器
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
如果发现后端,建议匹配的 SDK 技能:
| 检测到的后端 | 建议技能 |
|---|---|
Go (go.mod) | sentry-go-sdk |
Python (requirements.txt, pyproject.toml) | sentry-python-sdk |
Ruby (Gemfile) | sentry-ruby-sdk |
Java/Kotlin (pom.xml, build.gradle) | 参见 docs.sentry.io/platforms/java/ |
| Node.js (Express, Fastify, Hapi) | @sentry/node — 参见 docs.sentry.io/platforms/javascript/guides/express/ |
使用相同的 DSN 或链接的项目连接前端和后端,可以实现分布式追踪——在一个追踪视图中跨越浏览器、Next.js 服务器和后端 API 的堆栈跟踪。
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 事件未出现 | DSN 配置错误或 debug: false 隐藏了错误 | 临时设置 debug: true;检查浏览器网络选项卡中对 sentry.io 的请求 |
| 堆栈跟踪显示压缩代码 | 源映射未上传 | 检查 SENTRY_AUTH_TOKEN 是否已设置;运行 next build 并在构建输出中查找“Source Maps” |
onRequestError 未触发 | SDK 版本 < 8.28.0 | 升级:npm install @sentry/nextjs@latest |
| Edge 运行时错误缺失 | sentry.edge.config.ts 未加载 | 验证 instrumentation.ts 在 NEXT_RUNTIME === "edge" 时是否导入它 |
| 隧道路由返回 404 | 设置了 tunnelRoute 但缺少 Next.js 路由 | 插件会自动创建它;检查在添加 tunnelRoute 后是否运行了 next build |
withSentryConfig 摇树优化导致构建失败 | 使用 Turbopack | 摇树优化选项仅适用于 webpack;使用 Turbopack 时移除 webpack.treeshake 选项 |
global-error.tsx 未捕获错误 | 缺少 "use client" 指令 | 在 global-error.tsx 的第一行添加 "use client" |
| 会话回放未录制 | 客户端初始化中缺少 replayIntegration() | 在 instrumentation-client.ts 的 integrations 中添加 Sentry.replayIntegration() |
每周安装量
328
代码库
GitHub 星标
82
首次出现
2026年2月28日
安全审计
安装于
opencode326
github-copilot325
gemini-cli324
codex324
kimi-cli323
cursor323
All Skills > SDK Setup > 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.
@sentry/nextjsinstrumentation.ts, withSentryConfig(), or global-error.tsxNote: 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.
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:
| Question | Impact |
|---|---|
| Next.js version? | 13+ required; 15+ needed for Turbopack support |
| App Router or Pages Router? | Determines error boundary files needed (global-error.tsx vs _error.tsx) |
@sentry/nextjs already present? | Skip install, go to feature config |
Existing instrumentation.ts? | Merge Sentry into it rather than replace |
| Turbopack in use? | Tree-shaking in withSentryConfig is webpack-only |
| Logging library detected? | Recommend Sentry Logs integration |
Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage):
Optional (enhanced observability):
Sentry.logger.*; recommend when pino/winston or log search is neededDocument-Policy: js-profiling headerSentry.metrics.*; recommend when custom KPIs or business metrics neededRecommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| Tracing | Always for Next.js — server route tracing + client navigation are high-value |
| Session Replay | User-facing app, login flows, or checkout pages |
| Logging | App uses structured logging or needs log-to-trace correlation |
| Profiling | Performance-critical app; client sets Document-Policy: js-profiling |
| AI Monitoring | App makes OpenAI, Vercel AI SDK, or Anthropic calls |
| Crons | App has Vercel Cron jobs, scheduled API routes, or node-cron usage |
| Metrics | App 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?"
You need to run this yourself — the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:
npx @sentry/wizard@latest -i nextjsIt handles login, org/project selection, SDK installation, config files (
instrumentation-client.ts,sentry.server.config.ts,sentry.edge.config.ts,instrumentation.ts),next.config.tswrapping, source map upload, and adds a/sentry-example-page.Once it finishes, come back and skip toVerification.
If the user skips the wizard, proceed with Option 2 (Manual Setup) below.
npm install @sentry/nextjs --save
instrumentation-client.ts — Browser / Client RuntimeOlder docs used
sentry.client.config.ts— the current pattern isinstrumentation-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;
sentry.server.config.ts — Node.js Server Runtimeimport * 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,
});
sentry.edge.config.ts — Edge Runtimeimport * 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,
});
instrumentation.ts — Server-Side Registration HookRequires
experimental.instrumentationHook: trueinnext.configfor 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/global-error.tsxThis 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/_error.tsximport * 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);
};
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,
});
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 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: VerifyauthToken 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.
Load the corresponding reference file and follow its steps:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | references/error-monitoring.md | Always (baseline) — App Router error boundaries, Pages Router _error.tsx, server action wrapping |
| Tracing | 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 capture |
| Logging |
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
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:
| Check | How |
|---|---|
| Client errors captured | Throw in a client component, verify in Sentry |
| Server errors captured | Throw in a server action or API route |
| Edge errors captured | Throw in middleware or edge route handler |
| Source maps working | Check stack trace shows readable file names |
| Session Replay working | Check Replays tab in Sentry dashboard |
Sentry.init() Options| Option | Type | Default | Notes |
|---|---|---|---|
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 |
withSentryConfig() Options| Option | Type | Notes |
|---|---|---|
org | string | Sentry organization slug |
project | string | Sentry project slug |
authToken | string | Source map upload token (SENTRY_AUTH_TOKEN) |
| Variable | Runtime | Purpose |
|---|---|---|
NEXT_PUBLIC_SENTRY_DSN | Client | DSN for browser Sentry init (public) |
SENTRY_DSN | Server / Edge | DSN for server/edge Sentry init |
SENTRY_AUTH_TOKEN | Build | Source map upload auth token (secret) |
SENTRY_ORG | Build | Org slug (alternative to org in config) |
SENTRY_PROJECT |
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 detected | Suggest skill |
|---|---|
Go (go.mod) | sentry-go-sdk |
Python (requirements.txt, pyproject.toml) | sentry-python-sdk |
Ruby (Gemfile) | sentry-ruby-sdk |
Java/Kotlin (pom.xml, ) |
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.
| Issue | Cause | Solution |
|---|---|---|
| Events not appearing | DSN misconfigured or debug: false hiding errors | Set debug: true temporarily; check browser network tab for requests to sentry.io |
| Stack traces show minified code | Source maps not uploading | Check SENTRY_AUTH_TOKEN is set; run next build and look for "Source Maps" in build output |
onRequestError not firing | SDK version < 8.28.0 | Upgrade: |
Weekly Installs
328
Repository
GitHub Stars
82
First Seen
Feb 28, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode326
github-copilot325
gemini-cli324
codex324
kimi-cli323
cursor323
Next.js 16+ 缓存组件指南:实现部分预渲染(PPR)与混合内容缓存
13,200 周安装
| Backend directory found? | Trigger Phase 4 cross-link suggestion |
references/logging.mdStructured logs, Sentry.logger.*, log-to-trace correlation |
| Profiling | references/profiling.md | Continuous profiling, Document-Policy header, nodeProfilingIntegration |
| AI Monitoring | references/ai-monitoring.md | App uses OpenAI, Vercel AI SDK, or Anthropic |
| Crons | references/crons.md | Vercel Cron, scheduled API routes, node-cron |
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 | auto | Set to commit SHA or version tag |
debug | boolean | false | Log SDK activity to console |
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) |
| Build |
Project slug (alternative to project in config) |
SENTRY_RELEASE | Server | Release version string (auto-detected from git) |
NEXT_RUNTIME | Server / Edge | "nodejs" or "edge" (set by Next.js internally) |
build.gradle| See docs.sentry.io/platforms/java/ |
| Node.js (Express, Fastify, Hapi) | @sentry/node — see docs.sentry.io/platforms/javascript/guides/express/ |
npm install @sentry/nextjs@latest| Edge runtime errors missing | sentry.edge.config.ts not loaded | Verify instrumentation.ts imports it when NEXT_RUNTIME === "edge" |
| Tunnel route returns 404 | tunnelRoute set but Next.js route missing | The plugin creates it automatically; check you ran next build after adding tunnelRoute |
withSentryConfig tree-shaking breaks build | Turbopack in use | Tree-shaking options only work with webpack; remove webpack.treeshake options when using Turbopack |
global-error.tsx not catching errors | Missing "use client" directive | Add "use client" as the very first line of global-error.tsx |
| Session Replay not recording | replayIntegration() missing from client init | Add Sentry.replayIntegration() to integrations in instrumentation-client.ts |