sentry-nextjs-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSentry Next.js SDK
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.
这是一个预设规则的向导工具,会扫描你的Next.js项目,并引导你完成在浏览器、Node.js服务器和Edge这三个运行时环境中的完整Sentry配置。
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, orwithSentryConfig()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 (≥8.28.0). Always verify against docs.sentry.io/platforms/javascript/guides/nextjs/ before implementing.@sentry/nextjs
- 用户要求「为Next.js添加Sentry」或在Next.js应用中「设置Sentry」
- 用户想要安装或配置
@sentry/nextjs - 用户想要为Next.js配置错误监控、链路追踪、会话重放、日志记录或性能分析
- 用户询问、
instrumentation.ts或withSentryConfig()相关问题global-error.tsx - 用户想要捕获服务器操作、服务器组件错误或Edge运行时错误
注意: 以下SDK版本和API基于编写时的最新Sentry文档(≥8.28.0)。 实施前请务必对照Sentry官方文档进行验证。@sentry/nextjs
Phase 1: Detect
阶段1:检测
Run these commands to understand the project before making any recommendations:
bash
undefined执行以下命令,在给出建议前先了解项目情况:
bash
undefinedDetect Next.js version and existing Sentry
检测Next.js版本和已有的Sentry配置
cat package.json | grep -E '"next"|"@sentry/'
cat package.json | grep -E '"next"|"@sentry/'
Detect router type (App Router vs Pages Router)
检测路由类型(App Router 或 Pages Router)
ls src/app app src/pages pages 2>/dev/null
ls src/app app src/pages pages 2>/dev/null
Check for existing Sentry config files
检查是否存在现有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
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
检查next.config配置文件
ls next.config.ts next.config.js next.config.mjs 2>/dev/null
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
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"'
cat package.json | grep -E '"turbopack"|"webpack"'
Check for logging libraries
检查日志库
cat package.json | grep -E '"pino"|"winston"|"bunyan"'
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 |
| Backend directory found? | Trigger Phase 4 cross-link suggestion |
---ls ../backend ../server ../api 2>/dev/null
cat ../go.mod ../requirements.txt ../Gemfile 2>/dev/null | head -3
**需要确定的信息:**
| 问题 | 影响 |
|----------|--------|
| Next.js版本? | 要求13+版本;15+版本才支持Turbopack |
| 使用App Router还是Pages Router? | 决定所需的错误边界文件(`global-error.tsx` 或 `_error.tsx`) |
| 是否已安装`@sentry/nextjs`? | 跳过安装步骤,直接进入功能配置 |
| 是否存在现有`instrumentation.ts`? | 将Sentry配置合并到现有文件中,而非替换 |
| 是否使用Turbopack? | `withSentryConfig`中的摇树优化仅支持webpack |
| 检测到日志库? | 推荐集成Sentry Logs功能 |
| 发现后端目录? | 触发阶段4的跨服务关联建议 |
---Phase 2: Recommend
阶段2:推荐方案
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 ; recommend when
Sentry.logger.*/pinoor log search is neededwinston - ⚡ Profiling — continuous profiling; requires header
Document-Policy: js-profiling - ⚡ 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 ; recommend when custom KPIs or business metrics needed
Sentry.metrics.*
Recommendation 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 |
| AI Monitoring | App makes OpenAI, Vercel AI SDK, or Anthropic calls |
| Crons | App has Vercel Cron jobs, scheduled API routes, or |
| Metrics | App needs custom counters, gauges, or histograms via |
Propose: "I recommend setting up Error Monitoring + Tracing + Session Replay. Want me to also add Logging or Profiling?"
根据检测结果给出具体建议,不要提出开放式问题,直接给出方案:
推荐(核心覆盖):
- ✅ 错误监控 — 必选;捕获服务器错误、客户端错误、服务器操作和未处理的Promise拒绝
- ✅ 链路追踪 — 服务器端请求追踪 + 客户端导航链路,覆盖所有运行时
- ✅ 会话重放 — 面向用户的应用推荐;记录错误发生前后的用户会话
可选(增强可观测性):
- ⚡ 日志记录 — 通过实现结构化日志;当使用
Sentry.logger.*/pino或需要日志搜索时推荐winston - ⚡ 性能分析 — 持续性能分析;需要设置响应头
Document-Policy: js-profiling - ⚡ AI监控 — 支持OpenAI、Vercel AI SDK、Anthropic;当检测到AI/LLM调用时推荐
- ⚡ 定时任务监控 — 检测遗漏/失败的定时任务;当检测到定时任务规则时推荐
- ⚡ 指标监控 — 通过自定义指标;当需要自定义KPI或业务指标时推荐
Sentry.metrics.*
推荐逻辑:
| 功能 | 推荐场景 |
|---|---|
| 错误监控 | 始终必选 — 基础监控,不可或缺 |
| 链路追踪 | Next.js应用始终必选 — 服务器路由追踪和客户端导航的价值极高 |
| 会话重放 | 面向用户的应用、登录流程或结账页面 |
| 日志记录 | 应用使用结构化日志或需要日志与链路关联 |
| 性能分析 | 性能敏感型应用;客户端已设置 |
| AI监控 | 应用调用OpenAI、Vercel AI SDK或Anthropic服务 |
| 定时任务监控 | 应用使用Vercel Cron、定时API路由或 |
| 指标监控 | 应用需要通过 |
建议话术:“我建议设置错误监控 + 链路追踪 + 会话重放。是否需要同时添加日志记录或性能分析功能?”
Phase 3: Guide
阶段3:配置指引
Option 1: Wizard (Recommended)
选项1:向导工具(推荐)
bash
npx @sentry/wizard@latest -i nextjsThe 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 (, , , ), wraps with , configures source map upload, and adds a for verification.
instrumentation-client.tssentry.server.config.tssentry.edge.config.tsinstrumentation.tsnext.config.tswithSentryConfig()/sentry-example-pageSkip to Verification after running the wizard.
bash
npx @sentry/wizard@latest -i nextjs该向导会引导你完成登录、选择组织/项目和设置认证令牌的交互式流程 — 无需手动创建令牌。随后它会自动安装SDK、创建所有必要的配置文件(、、、)、用包装、配置源码映射上传,并添加一个用于验证的页面。
instrumentation-client.tssentry.server.config.tssentry.edge.config.tsinstrumentation.tswithSentryConfig()next.config.ts/sentry-example-page运行向导后直接跳转到验证步骤
Option 2: Manual Setup
选项2:手动配置
Install
安装SDK
bash
npm install @sentry/nextjs --savebash
npm install @sentry/nextjs --saveCreate instrumentation-client.ts
— Browser / Client Runtime
instrumentation-client.ts创建instrumentation-client.ts
— 浏览器/客户端运行时
instrumentation-client.tsOlder docs used— the current pattern issentry.client.config.ts.instrumentation-client.ts
typescript
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.client.config.ts。instrumentation-client.ts
typescript
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;Create sentry.server.config.ts
— Node.js Server Runtime
sentry.server.config.ts创建sentry.server.config.ts
— Node.js服务器运行时
sentry.server.config.tstypescript
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,
});typescript
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,
});Create sentry.edge.config.ts
— Edge Runtime
sentry.edge.config.ts创建sentry.edge.config.ts
— Edge运行时
sentry.edge.config.tstypescript
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,
});typescript
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
instrumentation.ts创建instrumentation.ts
— 服务器端注册钩子
instrumentation.tsRequiresinexperimental.instrumentationHook: truefor Next.js < 14.0.4. It's stable in 14.0.4+.next.config
typescript
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:
| Config file loaded |
|---|---|
| |
| |
| (client bundle) | |
Next.js <14.0.4版本需要在中设置next.config。14.0.4+版本已稳定支持该配置。experimental.instrumentationHook: true
typescript
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;运行时分发逻辑:
| 加载的配置文件 |
|---|---|
| |
| |
| (客户端包) | |
App Router: Create app/global-error.tsx
app/global-error.tsxApp Router:创建app/global-error.tsx
app/global-error.tsxThis catches errors in the root layout and React render errors:
tsx
"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>
);
}该组件会捕获根布局中的错误和React渲染错误:
tsx
"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
pages/_error.tsxPages Router:更新pages/_error.tsx
pages/_error.tsxtsx
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);
};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()
next.config.tswithSentryConfig()用withSentryConfig()
包装next.config.ts
withSentryConfig()next.config.tstypescript
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,
});typescript
import 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,
});Exclude Tunnel Route from Middleware
从中间件中排除隧道路由
If you have , exclude the tunnel path from auth or redirect logic:
middleware.tstypescript
// middleware.ts
export const config = {
matcher: [
// Exclude monitoring route, Next.js internals, and static files
"/((?!monitoring|_next/static|_next/image|favicon.ico).*)",
],
};如果你使用了,请将隧道路径从认证或重定向逻辑中排除:
middleware.tstypescript
// middleware.ts
export const config = {
matcher: [
// 排除监控路由、Next.js内部文件和静态文件
"/((?!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
Step 2: Set environment variables
bash
undefined源码映射可以让生产环境的栈追踪更易读 — 没有它,你只能看到压缩后的代码。这对生产环境应用来说是必不可少的。
步骤1:生成Sentry认证令牌
步骤2:设置环境变量
bash
undefined.env.sentry-build-plugin (gitignore this file)
.env.sentry-build-plugin (将此文件加入.gitignore)
SENTRY_AUTH_TOKEN=sntrys_eyJ...
Or set in CI secrets:
```bash
SENTRY_AUTH_TOKEN=sntrys_eyJ...
SENTRY_ORG=my-org # optional if set in next.config
SENTRY_PROJECT=my-project # optional if set in next.configStep 3: Add to
.gitignore.env.sentry-build-pluginStep 4: Verify is wired in
authTokennext.config.tstypescript
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 buildSENTRY_AUTH_TOKEN=sntrys_eyJ...
或者在CI环境的密钥中设置:
```bash
SENTRY_AUTH_TOKEN=sntrys_eyJ...
SENTRY_ORG=my-org # 如果在next.config中已设置则可选
SENTRY_PROJECT=my-project # 如果在next.config中已设置则可选步骤3:将文件加入
.gitignore.env.sentry-build-plugin步骤4:验证已在中配置
authTokennext.config.tstypescript
withSentryConfig(nextConfig, {
org: "my-org",
project: "my-project",
authToken: process.env.SENTRY_AUTH_TOKEN, // 从.env.sentry-build-plugin或CI环境变量读取
widenClientFileUpload: true,
});每次执行时,源码映射会自动上传。
next buildFor Each Agreed Feature
针对每个确认的功能
Load the corresponding reference file and follow its steps:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) — App Router error boundaries, Pages Router |
| Tracing | | Server-side request tracing, client navigation, distributed tracing, |
| Session Replay | | User-facing app; privacy masking, canvas recording, network capture |
| Logging | | Structured logs, |
| Profiling | | Continuous profiling, |
| AI Monitoring | | App uses OpenAI, Vercel AI SDK, or Anthropic |
| Crons | | Vercel Cron, scheduled API routes, |
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
加载对应的参考文件并按照步骤操作:
| 功能 | 参考文件 | 加载场景 |
|---|---|---|
| 错误监控 | | 始终加载(基础功能) — App Router错误边界、Pages Router |
| 链路追踪 | | 服务器端请求追踪、客户端导航、分布式追踪、 |
| 会话重放 | | 面向用户的应用;隐私掩码、画布录制、网络捕获 |
| 日志记录 | | 结构化日志、 |
| 性能分析 | | 持续性能分析、 |
| AI监控 | | 应用使用OpenAI、Vercel AI SDK或Anthropic |
| 定时任务监控 | | Vercel Cron、定时API路由、 |
对于每个功能:读取参考文件,严格按照步骤操作,并在进行下一步前完成验证。
Verification
验证
After wizard or manual setup, verify Sentry is working:
typescript
// 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是否正常工作:
typescript
// 临时添加到服务器操作或API路由中,验证后删除
import * as Sentry from "@sentry/nextjs";
throw new Error("Sentry测试错误 — 请删除此代码");
// 或者
Sentry.captureException(new Error("Sentry测试错误 — 请删除此代码"));然后查看你的Sentry问题仪表盘 — 错误应该会在约30秒内显示。
验证清单:
| 检查项 | 验证方式 |
|---|---|
| 客户端错误是否被捕获 | 在客户端组件中抛出错误,在Sentry中验证 |
| 服务器错误是否被捕获 | 在服务器操作或API路由中抛出错误 |
| Edge错误是否被捕获 | 在中间件或Edge路由处理函数中抛出错误 |
| 源码映射是否生效 | 检查栈追踪是否显示可读的文件名 |
| 会话重放是否生效 | 检查Sentry仪表盘中的重放标签页 |
Config Reference
配置参考
Sentry.init()
Options
Sentry.init()Sentry.init()
选项
Sentry.init()| Option | Type | Default | Notes |
|---|---|---|---|
| | — | Required. Use |
| | — | 0–1; 1.0 in dev, 0.1 in prod recommended |
| | | Fraction of all sessions recorded |
| | | Fraction of error sessions recorded |
| | | Include IP, request headers in events |
| | | Attach local variable values to stack frames (server only) |
| | | Enable Sentry Logs product |
| | auto | |
| | auto | Set to commit SHA or version tag |
| | | Log SDK activity to console |
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | — | 必填。客户端使用 |
| | — | 0–1;推荐开发环境1.0,生产环境0.1 |
| | | 记录的会话比例 |
| | | 错误会话的记录比例 |
| | | 在事件中包含IP、请求头信息 |
| | | 为栈帧附加局部变量值(仅服务器端) |
| | | 启用Sentry Logs功能 |
| | 自动 | 如 |
| | 自动 | 设置为提交SHA或版本标签 |
| | | 在控制台中打印SDK活动日志 |
withSentryConfig()
Options
withSentryConfig()withSentryConfig()
选项
withSentryConfig()| Option | Type | Notes |
|---|---|---|
| | Sentry organization slug |
| | Sentry project slug |
| | Source map upload token ( |
| | Upload more client files for better stack traces |
| | API route path for ad-blocker bypass (e.g. |
| | Suppress build output ( |
| | Tree-shake SDK features (webpack only, not Turbopack) |
| 选项 | 类型 | 说明 |
|---|---|---|
| | Sentry组织标识 |
| | Sentry项目标识 |
| | 源码映射上传令牌( |
| | 上传更多客户端文件以获得更清晰的栈追踪 |
| | 用于绕过广告拦截器的API路由路径(如 |
| | 抑制构建输出(推荐设置为 |
| | 摇树优化SDK功能(仅支持webpack,不支持Turbopack) |
Environment Variables
环境变量
| Variable | Runtime | Purpose |
|---|---|---|
| Client | DSN for browser Sentry init (public) |
| Server / Edge | DSN for server/edge Sentry init |
| Build | Source map upload auth token (secret) |
| Build | Org slug (alternative to |
| Build | Project slug (alternative to |
| Server | Release version string (auto-detected from git) |
| Server / Edge | |
| 变量 | 运行时 | 用途 |
|---|---|---|
| 客户端 | 浏览器端Sentry初始化的DSN(公开) |
| 服务器/Edge | 服务器/Edge端Sentry初始化的DSN |
| 构建阶段 | 源码映射上传认证令牌(保密) |
| 构建阶段 | 组织标识(替代配置文件中的 |
| 构建阶段 | 项目标识(替代配置文件中的 |
| 服务器 | 版本字符串(从Git自动检测) |
| 服务器/Edge | |
Phase 4: Cross-Link
阶段4:跨服务关联
After completing Next.js setup, check for companion services:
bash
undefined完成Next.js配置后,检查是否存在配套服务:
bash
undefinedCheck for backend services in adjacent directories
检查相邻目录中的后端服务
ls ../backend ../server ../api ../services 2>/dev/null
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`, `build.gradle`) | See [docs.sentry.io/platforms/java/](https://docs.sentry.io/platforms/java/) |
| Node.js (Express, Fastify, Hapi) | `@sentry/node` — see [docs.sentry.io/platforms/javascript/guides/express/](https://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.
---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`) | 查看[Sentry Java文档](https://docs.sentry.io/platforms/java/) |
| Node.js (Express, Fastify, Hapi) | `@sentry/node` — 查看[Sentry Express文档](https://docs.sentry.io/platforms/javascript/guides/express/) |
使用相同的DSN或关联项目连接前端和后端,可实现**分布式追踪** — 在单个追踪视图中查看跨越浏览器、Next.js服务器和后端API的完整栈追踪。
---Troubleshooting
故障排除
| Issue | Cause | Solution |
|---|---|---|
| Events not appearing | DSN misconfigured or | Set |
| Stack traces show minified code | Source maps not uploading | Check |
| SDK version < 8.28.0 | Upgrade: |
| Edge runtime errors missing | | Verify |
| Tunnel route returns 404 | | The plugin creates it automatically; check you ran |
| Turbopack in use | Tree-shaking options only work with webpack; remove |
| Missing | Add |
| Session Replay not recording | | Add |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 事件未显示 | DSN配置错误或 | 临时设置 |
| 栈追踪显示压缩代码 | 源码映射未上传 | 检查 |
| SDK版本 <8.28.0 | 升级SDK: |
| Edge运行时错误缺失 | | 验证 |
| 隧道路由返回404 | 设置了 | 插件会自动创建该路由;检查添加 |
| 使用了Turbopack | 摇树优化仅支持webpack;使用Turbopack时移除 |
| 缺少 | 在 |
| 会话重放未录制 | 客户端初始化时缺少 | 在 |