关于 sentry-nextjs-sdk
面向配置 Next.js 项目监控的引导技能,适用于需要覆盖浏览器、Node.js 服务端和 Edge 运行时的开发者。它检查项目结构,并指导 SDK 安装、配置、功能选择与验证。
主要功能
- 01检测 Next.js 版本和路由类型
- 02指导配置三种运行时
- 03配置监控与可观测性功能
- 04提供向导和手动设置流程
- 05指导上传源映射
适用场景
- 01在 Next.js 应用中配置 Sentry
- 02根据项目需求选择监控功能
- 03为生产构建添加源映射
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ getsentry/ sentry-for-ai --skill sentry-nextjs-sdk安装后在 Claude Code 中输入/sentry-nextjs-sdk确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/ai-monitoring.mdcrons.mderror-monitoring.mdlogging.mdmetrics.mdprofiling.mdsession-replay.mdtracing.md详细介绍
Sentry Next.js SDK
这款向导以明确的方式扫描 Next.js 项目,并指导你完成 Sentry 的全面设置,覆盖全部三个运行时:浏览器、Node.js 服务端和 Edge。
在以下情况下调用此技能
- 用户要求“在 Next.js 中添加 Sentry”或在 Next.js 应用中“设置 Sentry”
- 用户想安装或配置
@sentry/nextjs - 用户想为 Next.js 添加错误监控、追踪、会话回放、日志或性能分析
- 用户询问
instrumentation.ts、withSentryConfig()或global-error.tsx - 用户想捕获服务端操作、服务端组件错误或 Edge 运行时错误
注意: 以下 SDK 版本和 API 反映了本文撰写时 Sentry 文档中的当前内容(
@sentry/nextjs≥8.28.0)。 实施前,请务必对照 docs.sentry.io/platforms/javascript/guides/nextjs/ 进行验证。
阶段 1:检测
在提出任何建议之前,运行以下命令了解项目:
# 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
需要确定的内容:
| 问题 | 影响 |
|---|---|
| Next.js 版本? | 需要 13+;Turbopack 支持需要 15+ |
| 使用 App Router 还是 Pages Router? | 决定所需的错误边界文件(global-error.tsx 或 _error.tsx) |
是否已包含 @sentry/nextjs? | 跳过安装,转到功能配置 |
是否已有 instrumentation.ts? | 将 Sentry 合并到其中,而不是替换它 |
| 是否在使用 Turbopack? | withSentryConfig 中的树摇仅适用于 webpack |
| 是否检测到日志库? | 建议集成 Sentry Logs |
| 是否找到后端目录? | 触发阶段 4 的交叉链接建议 |
阶段 2:建议
根据发现的情况给出具体建议。不要提出开放式问题——直接给出方案:
推荐(核心覆盖):
- ✅ 错误监控 — 始终启用;捕获服务端错误、客户端错误、服务端操作错误和未处理的 Promise 拒绝
- ✅ 追踪 — 在所有运行时提供服务端请求追踪和客户端导航跨度
- ✅ 会话回放 — 面向用户的应用建议启用;记录发生错误时附近的会话
可选(增强可观测性):
- ⚡ 日志 — 通过
Sentry.logger.*记录结构化日志;使用pino/winston或需要搜索日志时建议启用 - ⚡ 性能分析 — 持续性能分析;需要
Document-Policy: js-profiling标头 - ⚡ AI 监控 — OpenAI、Vercel AI SDK、Anthropic;检测到 AI/LLM 调用时建议启用
- ⚡ 定时任务 — 检测遗漏或失败的定时任务;检测到 cron 模式时建议启用
- ⚡ 指标 — 通过
Sentry.metrics.*记录自定义指标;需要自定义 KPI 或业务指标时建议启用
建议逻辑:
| 功能 | 建议条件…… |
|---|---|
| 错误监控 | 始终启用 — 不可妥协的基础配置 |
| 追踪 | Next.js 始终启用 — 服务端路由追踪和客户端导航价值很高 |
| 会话回放 | 面向用户的应用、登录流程或结账页面 |
| 日志 | 应用使用结构化日志,或需要日志与追踪关联 |
| 性能分析 | 对性能要求高的应用;客户端设置了 Document-Policy: js-profiling |
| AI 监控 | 应用调用 OpenAI、Vercel AI SDK 或 Anthropic |
| 定时任务 | 应用使用 Vercel Cron 作业、定时 API 路由或 node-cron |
| 指标 | 应用需要通过 Sentry.metrics.* 记录自定义计数器、仪表盘或直方图 |
建议:“我建议设置错误监控 + 追踪 + 会话回放。还要我添加日志或性能分析吗?”
阶段 3:引导
选项 1:向导(推荐)
需要由你自行运行 — 向导会打开浏览器供你登录,并要求提供 Agent 无法处理的交互式输入。请复制粘贴到终端中:
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(手动设置)。
选项 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___",
dataCollection: {
// To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection
// userInfo: false,
// httpBodies: [],
},
// 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 服务端运行时
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
dataCollection: {
// To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection
// userInfo: false,
// httpBodies: [],
},
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 运行时
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
dataCollection: {
// To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/#dataCollection
// userInfo: false,
// httpBodies: [],
},
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");
}
}
// Automatically captures all unhandled server-side request errors
// Requires @sentry/nextjs >= 8.28.0
export const onRequestError = Sentry.captureRequestError;
运行时分派:
NEXT_RUNTIME | 加载的配置文件 |
|---|---|
"nodejs" | sentry.server.config.ts |
"edge" | sentry.edge.config.ts |
| (客户端 bundle) | instrumentation-client.ts(Next.js 会直接处理) |
App Router:创建 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 Router:更新 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);
};
使用 withSentryConfig() 包装 next.config.ts
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,
});
从中间件中排除隧道路由
如果你有 middleware.ts,请从身份验证或重定向逻辑中排除隧道路径:
// middleware.ts
export const config = {
matcher: [
// Exclude monitoring route, Next.js internals, and static files
"/((?!monitoring|_next/static|_next/image|favicon.ico).*)",
],
};
源映射设置
withSentryConfig 会在生产构建时上传源映射,以便堆栈跟踪显示原始代码,而非压缩后的输出。SDK 特定的接线配置是在 next.config.ts 中设置 authToken(以及可改善客户端堆栈跟踪的 widenClientFileUpload):
withSentryConfig(nextConfig, {
org: "my-org",
project: "my-project",
authToken: process.env.SENTRY_AUTH_TOKEN, // from CI env or a gitignored .env.sentry-build-plugin
widenClientFileUpload: true,
});
SENTRY_AUTH_TOKEN 是构建时密钥,与 DSN 不同。有关创建令牌、将其接入 CI 以及排查压缩后跟踪的问题,请参阅 sentry-source-maps。
每次运行 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 |
| 定时任务 | references/crons.md | Vercel Cron、计划 API 路由、node-cron |
| 指标 | references/metrics.md | 通过 Sentry.metrics.* 使用自定义计数器、仪表和分布 |
对于每项功能:阅读参考文件,严格遵循其中的步骤,并在继续之前进行验证。
配置参考
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 | 记录的错误会话所占比例 |
dataCollection | object | 未设置时为保守默认值 | 精细控制自动收集的类别(userInfo、cookies、httpHeaders、httpBodies、queryParams、genAI)。省略时,SDK 会回退到 sendDefaultPii(默认值为 false)。传入该对象(即使是 {})也会将未设置类别切换为宽松默认值;可按类别选择退出。 |
includeLocalVariables | boolean | false | 将局部变量值附加到堆栈帧(仅限服务端) |
enableLogs | boolean | false | 启用 Sentry Logs 产品 |
environment | string | 自动 | "production"、"staging" 等 |
release | string | 自动 | 设置为提交 SHA 或版本标签 |
debug | boolean | false | 将 SDK 活动记录到控制台 |
withSentryConfig() 选项
| 选项 | 类型 | 说明 |
|---|---|---|
org | string | Sentry 组织标识 |
project | string | Sentry 项目标识 |
authToken | string | Source Map 上传令牌(SENTRY_AUTH_TOKEN) |
widenClientFileUpload | boolean | 上传更多客户端文件,以获得更好的堆栈跟踪 |
tunnelRoute | string | 用于绕过广告拦截器的 API 路由路径(例如 "/monitoring") |
silent | boolean | 隐藏构建输出(建议使用 !process.env.CI) |
webpack.treeshake.* | object | 对 SDK 功能进行 Tree-shaking(仅限 webpack,不支持 Turbopack) |
环境变量
| 变量 | 运行时 | 用途 |
|---|---|---|
NEXT_PUBLIC_SENTRY_DSN | 客户端 | 浏览器 Sentry 初始化所用的 DSN(公开) |
SENTRY_DSN | 服务端 / Edge | 服务端/Edge Sentry 初始化所用的 DSN |
SENTRY_AUTH_TOKEN | 构建 | Source Map 上传身份验证令牌(机密) |
SENTRY_ORG | 构建 | 组织标识(可替代配置中的 org) |
SENTRY_PROJECT | 构建 | 项目标识(可替代配置中的 project) |
SENTRY_RELEASE | 服务端 | 发布版本字符串(从 git 自动检测) |
NEXT_RUNTIME | 服务端 / Edge | "nodejs" 或 "edge"(由 Next.js 在内部设置) |
验证
完成向导设置或手动设置后,请验证 Sentry 是否正常运行:
// 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"));
然后查看 Sentry Issues 仪表板——错误应会在约 30 秒内显示。
验证清单:
| 检查项 | 方法 |
|---|---|
| 已捕获客户端错误 | 在客户端组件中抛出错误,并在 Sentry 中确认 |
| 已捕获服务端错误 | 在服务端操作或 API 路由中抛出错误 |
| 已捕获 Edge 错误 | 在中间件或 Edge 路由处理程序中抛出错误 |
| Source Map 正常工作 | 检查堆栈跟踪是否显示易读的文件名 |
| Session Replay 正常工作 | 检查 Sentry 仪表板中的 Replays 选项卡 |
第 4 阶段:交叉关联
完成 Next.js 设置后,检查是否有配套服务:
# 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
如果检测到后端,请建议使用对应的 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" 指令 | 将 "use client" 添加到 global-error.tsx 的第一行 |
| Session Replay 未录制 | 客户端初始化中缺少 replayIntegration() | 将 Sentry.replayIntegration() 添加到 instrumentation-client.ts 中的 integrations |