sentry-nextjs-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

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项目,并引导你完成在浏览器、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
    ,
    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)。 实施前请务必对照Sentry官方文档进行验证。

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+版本;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
    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:向导工具(推荐)

bash
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.

bash
npx @sentry/wizard@latest -i nextjs
该向导会引导你完成登录、选择组织/项目和设置认证令牌的交互式流程 — 无需手动创建令牌。随后它会自动安装SDK、创建所有必要的配置文件(
instrumentation-client.ts
sentry.server.config.ts
sentry.edge.config.ts
instrumentation.ts
)、用
withSentryConfig()
包装
next.config.ts
、配置源码映射上传,并添加一个用于验证的
/sentry-example-page
页面。
运行向导后直接跳转到验证步骤

Option 2: Manual Setup

选项2:手动配置

Install

安装SDK

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
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
对于每个功能:读取参考文件,严格按照步骤操作,并在进行下一步前完成验证。

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仪表盘中的重放标签页

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`) | 查看[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

故障排除

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升级SDK:
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()