sentry-nextjs-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
All Skills > SDK Setup > Next.js SDK
所有技能 > SDK 设置 > Next.js SDK

Sentry 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项目,并引导你完成所有三个运行时的完整Sentry设置:浏览器、Node.js服务器和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.

  • 用户要求「为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/进行验证。

Phase 1: Detect

阶段1:检测

Run these commands to understand the project before making any recommendations:
bash
undefined
在给出任何建议前,运行以下命令了解项目情况:
bash
undefined

Detect 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+;支持Turbopack需要15+ |
| 使用App Router还是Pages Router? | 决定所需的错误边界文件(`global-error.tsx` vs `_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
    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 baseline
TracingAlways for Next.js — server route tracing + client navigation are high-value
Session ReplayUser-facing app, login flows, or checkout pages
LoggingApp uses structured logging or needs log-to-trace correlation
ProfilingPerformance-critical app; client sets
Document-Policy: js-profiling
AI MonitoringApp makes OpenAI, Vercel AI SDK, or Anthropic calls
CronsApp has Vercel Cron jobs, scheduled API routes, or
node-cron
usage
MetricsApp 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?"

基于检测结果给出具体建议,不要提出开放式问题,直接给出方案:
推荐(核心覆盖):
  • 错误监控 —— 必选;捕获服务器错误、客户端错误、服务器操作和未处理的Promise拒绝
  • 链路追踪 —— 服务器端请求追踪 + 所有运行时的客户端导航链路
  • 会话重放 —— 面向用户的应用推荐;记录错误发生前后的会话内容
可选(增强可观测性):
  • 日志记录 —— 通过
    Sentry.logger.*
    实现结构化日志;当检测到
    pino
    /
    winston
    或需要日志追踪关联时推荐
  • 性能分析 —— 持续性能分析;需要设置
    Document-Policy: js-profiling
    请求头
  • AI监控 —— 支持OpenAI、Vercel AI SDK、Anthropic;当检测到AI/LLM调用时推荐
  • 定时任务监控 —— 检测遗漏/失败的定时任务;当检测到定时任务模式时推荐
  • 自定义指标 —— 通过
    Sentry.metrics.*
    实现自定义指标;当需要自定义KPI或业务指标时推荐
推荐逻辑:
功能推荐场景
错误监控始终推荐 —— 不可缺少的基础功能
链路追踪Next.js应用始终推荐 —— 服务器路由追踪和客户端导航价值极高
会话重放面向用户的应用、登录流程或结账页面
日志记录应用使用结构化日志或需要日志与链路关联
性能分析性能敏感型应用;客户端已设置
Document-Policy: js-profiling
AI监控应用调用OpenAI、Vercel AI SDK或Anthropic服务
定时任务监控应用使用Vercel Cron任务、定时API路由或
node-cron
自定义指标应用需要通过
Sentry.metrics.*
实现自定义计数器、仪表盘或直方图
建议话术:「我推荐设置错误监控 + 链路追踪 + 会话重放。是否需要同时添加日志记录或性能分析功能?」

Phase 3: Guide

阶段3:引导

Option 1: Wizard (Recommended)

选项1:向导工具(推荐)

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 nextjs
It handles login, org/project selection, SDK installation, config files (
instrumentation-client.ts
,
sentry.server.config.ts
,
sentry.edge.config.ts
,
instrumentation.ts
),
next.config.ts
wrapping, source map upload, and adds a
/sentry-example-page
.
Once it finishes, come back and skip to Verification.
If the user skips the wizard, proceed with Option 2 (Manual Setup) below.

需要你自行运行 —— 向导会打开浏览器进行登录,需要交互式操作,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(手动设置)。

Option 2: Manual Setup

选项2:手动设置

Install

安装

bash
npm install @sentry/nextjs --save
bash
npm install @sentry/nextjs --save

Create
instrumentation-client.ts
— Browser / Client Runtime

创建
instrumentation-client.ts
—— 浏览器/客户端运行时

Older docs used
sentry.client.config.ts
— the current pattern is
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
—— Node.js服务器运行时

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,

  // 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
—— Edge运行时

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,
});
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
—— 服务器端注册钩子

Requires
experimental.instrumentationHook: true
in
next.config
for Next.js < 14.0.4. It's stable in 14.0.4+.
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:
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)
Next.js < 14.0.4版本需要在
next.config
中设置
experimental.instrumentationHook: true
。14.0.4+版本已稳定支持。
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;
运行时分发:
NEXT_RUNTIME
加载的配置文件
"nodejs"
sentry.server.config.ts
"edge"
sentry.edge.config.ts
(客户端打包)
instrumentation-client.ts
(Next.js直接处理)

App Router: Create
app/global-error.tsx

App Router:创建
app/global-error.tsx

This 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 Router:更新
pages/_error.tsx

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);
};
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()

使用
withSentryConfig()
包装
next.config.ts

typescript
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
middleware.ts
, exclude the tunnel path from auth or redirect logic:
typescript
// middleware.ts
export const config = {
  matcher: [
    // Exclude monitoring route, Next.js internals, and static files
    "/((?!monitoring|_next/static|_next/image|favicon.ico).*)",
  ],
};

如果使用
middleware.ts
,请将隧道路径从授权或重定向逻辑中排除:
typescript
// 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
Go to sentry.io/settings/auth-tokens/ and create a token with
project:releases
and
org:read
scopes.
Step 2: Set environment variables
bash
undefined
源映射可让生产环境的堆栈追踪可读 —— 没有源映射的话,你只能看到压缩后的代码。这对生产环境应用来说是必不可少的。
步骤1:生成Sentry授权令牌
访问sentry.io/settings/auth-tokens/,创建一个拥有
project:releases
org:read
权限的令牌。
步骤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.config
Step 3: Add to
.gitignore
.env.sentry-build-plugin
Step 4: Verify
authToken
is wired in
next.config.ts
typescript
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
.

SENTRY_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:验证
authToken
已在
next.config.ts
中配置
typescript
withSentryConfig(nextConfig, {
  org: "my-org",
  project: "my-project",
  authToken: process.env.SENTRY_AUTH_TOKEN, // 从.env.sentry-build-plugin或CI环境变量读取
  widenClientFileUpload: true,
});
每次执行
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 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
references/logging.md
Structured 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
Metrics
references/metrics.md
Custom counters, gauges, distributions via
Sentry.metrics.*
For each feature: read the reference file, follow its steps exactly, and verify before moving on.

加载对应的参考文件并遵循其步骤:
功能参考文件加载场景
错误监控
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.*
实现自定义计数器、仪表盘、分布统计
针对每个功能:读取参考文件,严格遵循其步骤,并在进行下一步前完成验证。

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:
CheckHow
Client errors capturedThrow in a client component, verify in Sentry
Server errors capturedThrow in a server action or API route
Edge errors capturedThrow in middleware or edge route handler
Source maps workingCheck stack trace shows readable file names
Session Replay workingCheck 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仪表板中的Replays标签页

Config Reference

配置参考

Sentry.init()
Options

Sentry.init()
选项

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
选项类型默认值说明
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
自动检测
"production"
"staging"
release
string
自动检测设置为提交SHA或版本标签
debug
boolean
false
在控制台记录SDK活动日志

withSentryConfig()
Options

withSentryConfig()
选项

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)
选项类型说明
org
string
Sentry组织别名
project
string
Sentry项目别名
authToken
string
源映射上传令牌(
SENTRY_AUTH_TOKEN
widenClientFileUpload
boolean
上传更多客户端文件以获得更清晰的堆栈追踪
tunnelRoute
string
用于绕过广告拦截器的API路由路径(如
"/monitoring"
silent
boolean
抑制构建输出(推荐设为
!process.env.CI
webpack.treeshake.*
object
摇树优化SDK功能(仅支持webpack,不支持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)

变量运行时用途
NEXT_PUBLIC_SENTRY_DSN
客户端浏览器端Sentry初始化的DSN(公开)
SENTRY_DSN
服务器/Edge服务器/Edge端Sentry初始化的DSN
SENTRY_AUTH_TOKEN
构建阶段源映射上传授权令牌(机密)
SENTRY_ORG
构建阶段组织别名(替代配置中的
org
SENTRY_PROJECT
构建阶段项目别名(替代配置中的
project
SENTRY_RELEASE
服务器版本字符串(从git自动检测)
NEXT_RUNTIME
服务器/Edge
"nodejs"
"edge"
(由Next.js内部设置)

Phase 4: Cross-Link

阶段4:跨服务关联

After completing Next.js setup, check for companion services:
bash
undefined
完成Next.js设置后,检查是否存在关联服务:
bash
undefined

Check 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`) | 查看[docs.sentry.io/platforms/java/](https://docs.sentry.io/platforms/java/) |
| Node.js (Express, Fastify, Hapi) | `@sentry/node` —— 查看[docs.sentry.io/platforms/javascript/guides/express/](https://docs.sentry.io/platforms/javascript/guides/express/) |

使用相同DSN或关联项目连接前端和后端,可实现**分布式追踪** —— 在单个追踪视图中查看跨浏览器、Next.js服务器和后端API的完整堆栈追踪。

---

Troubleshooting

故障排除

IssueCauseSolution
Events not appearingDSN misconfigured or
debug: false
hiding errors
Set
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 firing
SDK version < 8.28.0Upgrade:
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 useTree-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
问题原因解决方案
事件未显示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()