sentry-react-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Sentry React SDK

Sentry React SDK

Opinionated wizard that scans your React project and guides you through complete Sentry setup.
这是一个智能向导,会扫描你的React项目并引导你完成完整的Sentry配置流程。

Invoke This Skill When

触发此技能的场景

  • User asks to "add Sentry to React" or "set up Sentry" in a React app
  • User wants error monitoring, tracing, session replay, profiling, or logging in React
  • User mentions
    @sentry/react
    , React Sentry SDK, or Sentry error boundaries
  • User wants to monitor React Router navigation, Redux state, or component performance
Note: SDK versions and APIs below reflect current Sentry docs at time of writing (
@sentry/react
≥8.0.0). Always verify against docs.sentry.io/platforms/javascript/guides/react/ before implementing.

  • 用户要求「为React添加Sentry」或在React应用中「配置Sentry」
  • 用户需要为React应用实现错误监控、链路追踪、会话重放、性能分析或日志功能
  • 用户提及
    @sentry/react
    、React Sentry SDK或Sentry错误边界
  • 用户希望监控React Router导航、Redux状态或组件性能
注意: 以下SDK版本和API基于当前Sentry文档(编写时
@sentry/react
≥8.0.0)。 实施前请务必对照Sentry官方文档进行验证。

Phase 1: Detect

阶段一:项目检测

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

Detect React version

检测React版本

cat package.json | grep -E '"react"|"react-dom"'
cat package.json | grep -E '"react"|"react-dom"'

Check for existing Sentry

检查是否已安装Sentry

cat package.json | grep '"@sentry/'
cat package.json | grep '"@sentry/'

Detect router

检测路由库

cat package.json | grep -E '"react-router-dom"|"@tanstack/react-router"'
cat package.json | grep -E '"react-router-dom"|"@tanstack/react-router"'

Detect state management

检测状态管理库

cat package.json | grep -E '"redux"|"@reduxjs/toolkit"'
cat package.json | grep -E '"redux"|"@reduxjs/toolkit"'

Detect build tool

检测构建工具

ls vite.config.ts vite.config.js webpack.config.js craco.config.js 2>/dev/null cat package.json | grep -E '"vite"|"react-scripts"|"webpack"'
ls vite.config.ts vite.config.js webpack.config.js craco.config.js 2>/dev/null cat package.json | grep -E '"vite"|"react-scripts"|"webpack"'

Detect logging libraries

检测日志库

cat package.json | grep -E '"pino"|"winston"|"loglevel"'
cat package.json | grep -E '"pino"|"winston"|"loglevel"'

Check for companion backend in adjacent directories

检查相邻目录是否存在配套后端

ls ../backend ../server ../api 2>/dev/null cat ../go.mod ../requirements.txt ../Gemfile ../pom.xml 2>/dev/null | head -3

**What to determine:**

| Question | Impact |
|----------|--------|
| React 19+? | Use `reactErrorHandler()` hook pattern |
| React <19? | Use `Sentry.ErrorBoundary` |
| `@sentry/react` already present? | Skip install, go straight to feature config |
| `react-router-dom` v5 / v6 / v7? | Determines which router integration to use |
| `@tanstack/react-router`? | Use `tanstackRouterBrowserTracingIntegration()` |
| Redux in use? | Recommend `createReduxEnhancer()` |
| Vite detected? | Source maps via `sentryVitePlugin` |
| CRA (`react-scripts`)? | Source maps via `@sentry/webpack-plugin` in CRACO |
| Backend directory found? | Trigger Phase 4 cross-link suggestion |

---
ls ../backend ../server ../api 2>/dev/null cat ../go.mod ../requirements.txt ../Gemfile ../pom.xml 2>/dev/null | head -3

**需要确定的关键信息:**

| 问题 | 影响 |
|----------|--------|
| 是否为React 19+? | 使用`reactErrorHandler()`钩子模式 |
| 是否为React <19? | 使用`Sentry.ErrorBoundary`组件 |
| 是否已安装`@sentry/react`? | 跳过安装步骤,直接进入功能配置 |
| React Router版本是v5 / v6 / v7? | 决定使用对应的路由集成方案 |
| 是否使用`@tanstack/react-router`? | 使用`tanstackRouterBrowserTracingIntegration()` |
| 是否使用Redux? | 建议添加`createReduxEnhancer()` |
| 是否使用Vite? | 通过`sentryVitePlugin`配置Source Maps |
| 是否使用CRA(`react-scripts`)? | 在CRACO中通过`@sentry/webpack-plugin`配置Source Maps |
| 是否存在后端目录? | 触发阶段四的跨端配置建议 |

---

Phase 2: Recommend

阶段二:配置建议

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 unhandled errors, React error boundaries, React 19 hooks
  • Tracing — React SPAs benefit from page load, navigation, and API call tracing
  • Session Replay — recommended for user-facing apps; records sessions around errors
Optional (enhanced observability):
  • Logging — structured logs via
    Sentry.logger.*
    ; recommend when structured log search is needed
  • Profiling — JS Self-Profiling API (⚠️ experimental; requires cross-origin isolation headers)
Recommendation logic:
FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline
TracingAlways for React SPAs — page load + navigation spans are high-value
Session ReplayUser-facing app, login flows, or checkout pages
LoggingApp needs structured log search or log-to-trace correlation
ProfilingPerformance-critical app; server sends
Document-Policy: js-profiling
header
React-specific extras:
  • React 19 detected → set up
    reactErrorHandler()
    on
    createRoot
  • React Router detected → configure matching router integration (see Phase 3)
  • Redux detected → add
    createReduxEnhancer()
    to Redux store
  • Vite detected → configure
    sentryVitePlugin
    for source maps (essential for readable stack traces)
Propose: "I recommend setting up Error Monitoring + Tracing + Session Replay. Want me to also add Logging or Profiling?"

根据项目检测结果给出具体建议,避免开放式问题,直接提供方案:
推荐配置(核心覆盖):
  • 错误监控 —— 必选;捕获未处理错误、React错误边界、React 19钩子错误
  • 链路追踪 —— React单页应用必备,覆盖页面加载、导航和API调用追踪
  • 会话重放 —— 面向用户的应用推荐配置,可记录错误发生前后的会话内容
可选配置(增强可观测性):
  • 日志功能 —— 通过
    Sentry.logger.*
    实现结构化日志;当需要结构化日志搜索时推荐配置
  • 性能分析 —— 基于JS Self-Profiling API(⚠️ 实验性功能;需要跨源隔离头)
推荐逻辑:
功能推荐场景
错误监控必选 —— 基础监控能力,不可或缺
链路追踪React单页应用必选 —— 页面加载和导航链路的价值极高
会话重放面向用户的应用、登录流程或结账页面
日志功能应用需要结构化日志搜索或日志与链路关联
性能分析性能敏感型应用;服务器需发送
Document-Policy: js-profiling
响应头
React专属增强配置:
  • 检测到React 19 → 在
    createRoot
    上配置
    reactErrorHandler()
  • 检测到React Router → 配置对应的路由集成(见阶段三)
  • 检测到Redux → 为Redux Store添加
    createReduxEnhancer()
  • 检测到Vite → 配置
    sentryVitePlugin
    生成Source Maps(这是生成可读堆栈跟踪的关键)
建议话术:「我建议配置错误监控 + 链路追踪 + 会话重放。是否需要同时添加日志功能或性能分析?」

Phase 3: Guide

阶段三:分步引导

Install

安装SDK

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

Create
src/instrument.ts

创建
src/instrument.ts
文件

Sentry must initialize before any other code runs. Put
Sentry.init()
in a dedicated sidecar file:
typescript
import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: import.meta.env.VITE_SENTRY_DSN, // Adjust per build tool (see table below)
  environment: import.meta.env.MODE,
  release: import.meta.env.VITE_APP_VERSION, // inject at build time

  sendDefaultPii: true,

  integrations: [
    Sentry.browserTracingIntegration(),
    Sentry.replayIntegration({
      maskAllText: true,
      blockAllMedia: true,
    }),
  ],

  // Tracing
  tracesSampleRate: 1.0, // lower to 0.1–0.2 in production
  tracePropagationTargets: ["localhost", /^https:\/\/yourapi\.io/],

  // Session Replay
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,

  enableLogs: true,
});
DSN environment variable by build tool:
Build ToolVariable NameAccess in code
Vite
VITE_SENTRY_DSN
import.meta.env.VITE_SENTRY_DSN
Create React App
REACT_APP_SENTRY_DSN
process.env.REACT_APP_SENTRY_DSN
Custom webpack
SENTRY_DSN
process.env.SENTRY_DSN
Sentry必须在所有其他代码运行前初始化。将
Sentry.init()
放在独立的初始化文件中:
typescript
import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: import.meta.env.VITE_SENTRY_DSN, // 根据构建工具调整(见下表)
  environment: import.meta.env.MODE,
  release: import.meta.env.VITE_APP_VERSION, // 构建时注入版本号

  sendDefaultPii: true,

  integrations: [
    Sentry.browserTracingIntegration(),
    Sentry.replayIntegration({
      maskAllText: true,
      blockAllMedia: true,
    }),
  ],

  // 链路追踪配置
  tracesSampleRate: 1.0, // 生产环境建议调低至0.1–0.2
  tracePropagationTargets: ["localhost", /^https:\/\/yourapi\.io/],

  // 会话重放配置
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,

  enableLogs: true,
});
不同构建工具的DSN环境变量:
构建工具变量名称代码中获取方式
Vite
VITE_SENTRY_DSN
import.meta.env.VITE_SENTRY_DSN
Create React App
REACT_APP_SENTRY_DSN
process.env.REACT_APP_SENTRY_DSN
自定义webpack
SENTRY_DSN
process.env.SENTRY_DSN

Entry Point Setup

入口文件配置

Import
instrument.ts
as the very first import in your entry file:
tsx
// src/main.tsx (Vite) or src/index.tsx (CRA/webpack)
import "./instrument";              // ← MUST be first

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <App />
  </StrictMode>
);
在入口文件中第一个导入
instrument.ts
tsx
// src/main.tsx (Vite) 或 src/index.tsx (CRA/webpack)
import "./instrument";              // ← 必须是第一个导入

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <App />
  </StrictMode>
);

React Version-Specific Error Handling

不同React版本的错误处理

React 19+ — use
reactErrorHandler()
on
createRoot
:
tsx
import { reactErrorHandler } from "@sentry/react";

createRoot(document.getElementById("root")!, {
  onUncaughtError: reactErrorHandler(),
  onCaughtError: reactErrorHandler(),
  onRecoverableError: reactErrorHandler(),
}).render(<App />);
React <19 — wrap your app in
Sentry.ErrorBoundary
:
tsx
import * as Sentry from "@sentry/react";

createRoot(document.getElementById("root")!).render(
  <Sentry.ErrorBoundary fallback={<p>Something went wrong</p>} showDialog>
    <App />
  </Sentry.ErrorBoundary>
);
Use
<Sentry.ErrorBoundary>
for any sub-tree that should catch errors independently (route sections, widgets, etc.).
React 19+ —— 在
createRoot
上使用
reactErrorHandler()
tsx
import { reactErrorHandler } from "@sentry/react";

createRoot(document.getElementById("root")!, {
  onUncaughtError: reactErrorHandler(),
  onCaughtError: reactErrorHandler(),
  onRecoverableError: reactErrorHandler(),
}).render(<App />);
React <19 —— 用
Sentry.ErrorBoundary
包裹应用:
tsx
import * as Sentry from "@sentry/react";

createRoot(document.getElementById("root")!).render(
  <Sentry.ErrorBoundary fallback={<p>出现了一些问题</p>} showDialog>
    <App />
  </Sentry.ErrorBoundary>
);
对于需要独立捕获错误的子组件树(如路由模块、小组件等),也可以使用
<Sentry.ErrorBoundary>
包裹。

Router Integration

路由集成配置

Configure the matching integration for your router:
RouterIntegrationNotes
React Router v7
reactRouterV7BrowserTracingIntegration
useEffect
,
useLocation
,
useNavigationType
,
createRoutesFromChildren
,
matchRoutes
from
react-router
React Router v6
reactRouterV6BrowserTracingIntegration
useEffect
,
useLocation
,
useNavigationType
,
createRoutesFromChildren
,
matchRoutes
from
react-router-dom
React Router v5
reactRouterV5BrowserTracingIntegration
Wrap routes in
withSentryRouting(Route)
TanStack Router
tanstackRouterBrowserTracingIntegration(router)
Pass router instance — no hooks required
No router / custom
browserTracingIntegration()
Names transactions by URL path
React Router v6/v7 setup:
typescript
// in instrument.ts integrations array:
import React from "react";
import {
  createRoutesFromChildren, matchRoutes,
  useLocation, useNavigationType,
} from "react-router-dom"; // or "react-router" for v7
import * as Sentry from "@sentry/react";
import { reactRouterV6BrowserTracingIntegration } from "@sentry/react";
import { createBrowserRouter } from "react-router-dom";

// Option A — createBrowserRouter (recommended for v6.4+):
const sentryCreateBrowserRouter = Sentry.wrapCreateBrowserRouterV6(createBrowserRouter);
const router = sentryCreateBrowserRouter([...routes]);

// Option B — createBrowserRouter for React Router v7:
// const sentryCreateBrowserRouter = Sentry.wrapCreateBrowserRouterV7(createBrowserRouter);

// Option C — integration with hooks (v6 without data APIs):
Sentry.init({
  integrations: [
    reactRouterV6BrowserTracingIntegration({
      useEffect: React.useEffect,
      useLocation,
      useNavigationType,
      matchRoutes,
      createRoutesFromChildren,
    }),
  ],
});
TanStack Router setup:
typescript
import { tanstackRouterBrowserTracingIntegration } from "@sentry/react";

// Pass your TanStack router instance:
Sentry.init({
  integrations: [tanstackRouterBrowserTracingIntegration(router)],
});
根据使用的路由库配置对应的集成:
路由库集成方案说明
React Router v7
reactRouterV7BrowserTracingIntegration
需要从
react-router
导入
useEffect
useLocation
useNavigationType
createRoutesFromChildren
matchRoutes
React Router v6
reactRouterV6BrowserTracingIntegration
需要从
react-router-dom
导入
useEffect
useLocation
useNavigationType
createRoutesFromChildren
matchRoutes
React Router v5
reactRouterV5BrowserTracingIntegration
withSentryRouting(Route)
包裹路由
TanStack Router
tanstackRouterBrowserTracingIntegration(router)
传入TanStack Router实例 —— 无需钩子
无路由/自定义路由
browserTracingIntegration()
根据URL路径命名事务
React Router v6/v7配置:
typescript
// 在instrument.ts的integrations数组中配置:
import React from "react";
import {
  createRoutesFromChildren, matchRoutes,
  useLocation, useNavigationType,
} from "react-router-dom"; // v7版本从"react-router"导入
import * as Sentry from "@sentry/react";
import { reactRouterV6BrowserTracingIntegration } from "@sentry/react";
import { createBrowserRouter } from "react-router-dom";

// 方案A —— createBrowserRouter(v6.4+推荐):
const sentryCreateBrowserRouter = Sentry.wrapCreateBrowserRouterV6(createBrowserRouter);
const router = sentryCreateBrowserRouter([...routes]);

// 方案B —— React Router v7的createBrowserRouter:
// const sentryCreateBrowserRouter = Sentry.wrapCreateBrowserRouterV7(createBrowserRouter);

// 方案C —— 钩子集成(v6无数据API版本):
Sentry.init({
  integrations: [
    reactRouterV6BrowserTracingIntegration({
      useEffect: React.useEffect,
      useLocation,
      useNavigationType,
      matchRoutes,
      createRoutesFromChildren,
    }),
  ],
});
TanStack Router配置:
typescript
import { tanstackRouterBrowserTracingIntegration } from "@sentry/react";

// 传入你的TanStack Router实例:
Sentry.init({
  integrations: [tanstackRouterBrowserTracingIntegration(router)],
});

Redux Integration (when detected)

Redux集成(检测到Redux时)

typescript
import * as Sentry from "@sentry/react";
import { configureStore } from "@reduxjs/toolkit";

const store = configureStore({
  reducer: rootReducer,
  enhancers: (getDefaultEnhancers) =>
    getDefaultEnhancers().concat(Sentry.createReduxEnhancer()),
});
typescript
import * as Sentry from "@sentry/react";
import { configureStore } from "@reduxjs/toolkit";

const store = configureStore({
  reducer: rootReducer,
  enhancers: (getDefaultEnhancers) =>
    getDefaultEnhancers().concat(Sentry.createReduxEnhancer()),
});

Source Maps Setup (strongly recommended)

Source Maps配置(强烈推荐)

Without source maps, stack traces show minified code. Set up the build plugin to upload source maps automatically:
Vite (
vite.config.ts
):
typescript
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { sentryVitePlugin } from "@sentry/vite-plugin";

export default defineConfig({
  build: { sourcemap: "hidden" },
  plugins: [
    react(),
    sentryVitePlugin({
      org: process.env.SENTRY_ORG,
      project: process.env.SENTRY_PROJECT,
      authToken: process.env.SENTRY_AUTH_TOKEN,
    }),
  ],
});
Add to
.env
(never commit):
bash
SENTRY_AUTH_TOKEN=sntrys_...
SENTRY_ORG=my-org-slug
SENTRY_PROJECT=my-project-slug
Create React App (via CRACO):
bash
npm install @craco/craco @sentry/webpack-plugin --save-dev
javascript
// craco.config.js
const { sentryWebpackPlugin } = require("@sentry/webpack-plugin");

module.exports = {
  webpack: {
    plugins: {
      add: [
        sentryWebpackPlugin({
          org: process.env.SENTRY_ORG,
          project: process.env.SENTRY_PROJECT,
          authToken: process.env.SENTRY_AUTH_TOKEN,
        }),
      ],
    },
  },
};
没有Source Maps的话,堆栈跟踪会显示压缩后的代码。配置构建插件自动上传Source Maps:
Vite(
vite.config.ts
):
typescript
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { sentryVitePlugin } from "@sentry/vite-plugin";

export default defineConfig({
  build: { sourcemap: "hidden" },
  plugins: [
    react(),
    sentryVitePlugin({
      org: process.env.SENTRY_ORG,
      project: process.env.SENTRY_PROJECT,
      authToken: process.env.SENTRY_AUTH_TOKEN,
    }),
  ],
});
添加到
.env
文件(请勿提交到版本库):
bash
SENTRY_AUTH_TOKEN=sntrys_...
SENTRY_ORG=my-org-slug
SENTRY_PROJECT=my-project-slug
Create React App(通过CRACO):
bash
npm install @craco/craco @sentry/webpack-plugin --save-dev
javascript
// craco.config.js
const { sentryWebpackPlugin } = require("@sentry/webpack-plugin");

module.exports = {
  webpack: {
    plugins: {
      add: [
        sentryWebpackPlugin({
          org: process.env.SENTRY_ORG,
          project: process.env.SENTRY_PROJECT,
          authToken: process.env.SENTRY_AUTH_TOKEN,
        }),
      ],
    },
  },
};

For Each Agreed Feature

逐个功能配置

Walk through features one at a time. Load the reference file, follow its steps, verify before moving on:
FeatureReferenceLoad when...
Error Monitoring
${SKILL_ROOT}/references/error-monitoring.md
Always (baseline)
Tracing
${SKILL_ROOT}/references/tracing.md
SPA navigation / API call tracing
Session Replay
${SKILL_ROOT}/references/session-replay.md
User-facing app
Logging
${SKILL_ROOT}/references/logging.md
Structured log search / log-to-trace
Profiling
${SKILL_ROOT}/references/profiling.md
Performance-critical app
React Features
${SKILL_ROOT}/references/react-features.md
Redux, component tracking, source maps, integrations catalog
For each feature:
Read ${SKILL_ROOT}/references/<feature>.md
, follow steps exactly, verify it works.

逐个完成功能配置,每个功能都要参考对应文档,严格按照步骤操作并验证:
功能参考文档触发场景
错误监控
${SKILL_ROOT}/references/error-monitoring.md
必选(基础功能)
链路追踪
${SKILL_ROOT}/references/tracing.md
单页应用导航/API调用追踪
会话重放
${SKILL_ROOT}/references/session-replay.md
面向用户的应用
日志功能
${SKILL_ROOT}/references/logging.md
结构化日志搜索/日志与链路关联
性能分析
${SKILL_ROOT}/references/profiling.md
性能敏感型应用
React专属功能
${SKILL_ROOT}/references/react-features.md
Redux、组件追踪、Source Maps、集成目录
每个功能的配置流程:阅读
${SKILL_ROOT}/references/<feature>.md
,严格按照步骤操作,验证功能正常运行。

Configuration Reference

配置参考

Key
Sentry.init()
Options

Sentry.init()
关键配置项

OptionTypeDefaultNotes
dsn
string
Required. SDK disabled when empty
environment
string
"production"
e.g.,
"staging"
,
"development"
release
string
e.g.,
"my-app@1.0.0"
or git SHA — links errors to releases
sendDefaultPii
boolean
false
Includes IP addresses and request headers
tracesSampleRate
number
0–1;
1.0
in dev,
0.1–0.2
in prod
tracesSampler
function
Per-transaction sampling; overrides rate
tracePropagationTargets
(string|RegExp)[]
Outgoing URLs that receive distributed tracing headers
replaysSessionSampleRate
number
Fraction of all sessions recorded
replaysOnErrorSampleRate
number
Fraction of error sessions recorded
enableLogs
boolean
false
Enable
Sentry.logger.*
API
attachStacktrace
boolean
false
Stack traces on
captureMessage()
calls
maxBreadcrumbs
number
100
Breadcrumbs stored per event
debug
boolean
false
Verbose SDK output to console
tunnel
string
Proxy URL to bypass ad blockers
配置项类型默认值说明
dsn
string
必填。为空时SDK会禁用
environment
string
"production"
例如:
"staging"
"development"
release
string
例如:
"my-app@1.0.0"
或git提交哈希 —— 将错误与版本关联
sendDefaultPii
boolean
false
包含IP地址和请求头
tracesSampleRate
number
0–1;开发环境设为1.0,生产环境设为0.1–0.2
tracesSampler
function
按事务采样;优先级高于采样率
tracePropagationTargets
(string|RegExp)[]
接收分布式追踪头的外部URL
replaysSessionSampleRate
number
录制的会话比例
replaysOnErrorSampleRate
number
错误会话的录制比例
enableLogs
boolean
false
启用
Sentry.logger.*
API
attachStacktrace
boolean
false
captureMessage()
调用添加堆栈跟踪
maxBreadcrumbs
number
100
每个事件存储的面包屑数量
debug
boolean
false
在控制台输出详细的SDK日志
tunnel
string
代理URL,用于绕过广告拦截器

React Compatibility Matrix

React兼容性矩阵

React VersionError handling approachSDK minimum
React 19+
reactErrorHandler()
on
createRoot
@sentry/react
≥8.0.0
React 16–18
Sentry.ErrorBoundary
component
@sentry/react
≥7.0.0
React 16
componentDidCatch
class boundaries
@sentry/react
≥6.0.0

React版本错误处理方式最低SDK版本
React 19+
createRoot
上使用
reactErrorHandler()
@sentry/react
≥8.0.0
React 16–18使用
Sentry.ErrorBoundary
组件
@sentry/react
≥7.0.0
React 16使用
componentDidCatch
类组件边界
@sentry/react
≥6.0.0

Verification

验证配置

Trigger test events to confirm Sentry is receiving data:
tsx
// Add a temporary test button anywhere in your app
import * as Sentry from "@sentry/react";

function SentryTest() {
  return (
    <>
      <button onClick={() => { throw new Error("Sentry React test error"); }}>
        Test Error
      </button>
      <button onClick={() => Sentry.captureMessage("Sentry test message", "info")}>
        Test Message
      </button>
    </>
  );
}
Check the Sentry dashboard:
  • Issues → error appears within seconds
  • Traces → page load and navigation transactions visible
  • Replays → session recording visible after page interaction
  • Logs → structured log entries if logging enabled
Set
debug: true
in
Sentry.init()
and check the browser console if nothing appears.

触发测试事件确认Sentry是否正常接收数据:
tsx
// 在应用中临时添加测试按钮
import * as Sentry from "@sentry/react";

function SentryTest() {
  return (
    <>
      <button onClick={() => { throw new Error("Sentry React测试错误"); }}>
        测试错误上报
      </button>
      <button onClick={() => Sentry.captureMessage("Sentry测试消息", "info")}>
        测试消息上报
      </button>
    </>
  );
}
在Sentry控制台检查:
  • Issues → 错误会在几秒内出现
  • Traces → 可以看到页面加载和导航事务
  • Replays → 页面交互后可以看到会话录制内容
  • Logs → 如果启用了日志功能,可以看到结构化日志条目
如果没有数据,在
Sentry.init()
中设置
debug: true
并检查浏览器控制台。

Phase 4: Cross-Link

阶段四:跨端关联配置

After completing React setup, check for a companion backend missing Sentry coverage:
bash
ls ../backend ../server ../api ../go ../python 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 2>/dev/null | grep '<artifactId>' | head -3
If a backend exists without Sentry configured, suggest the matching skill:
Backend detectedSuggest skill
Go (
go.mod
)
sentry-go-sdk
Python (
requirements.txt
,
pyproject.toml
)
sentry-python-sdk
Ruby (
Gemfile
)
sentry-ruby-sdk
Java (
pom.xml
,
build.gradle
)
Use
@sentry/java
— see docs.sentry.io/platforms/java/
Node.js (Express, Fastify)Use
@sentry/node
— see docs.sentry.io/platforms/javascript/guides/express/

完成React端配置后,检查是否存在未配置Sentry的配套后端:
bash
ls ../backend ../server ../api ../go ../python 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 2>/dev/null | grep '<artifactId>' | head -3
如果存在未配置Sentry的后端,建议使用对应的技能:
检测到的后端推荐技能
Go(
go.mod
sentry-go-sdk
Python(
requirements.txt
pyproject.toml
sentry-python-sdk
Ruby(
Gemfile
sentry-ruby-sdk
Java(
pom.xml
build.gradle
使用
@sentry/java
—— 参考Sentry Java文档
Node.js(Express、Fastify)使用
@sentry/node
—— 参考Sentry Express文档

Troubleshooting

故障排查

IssueSolution
Events not appearingSet
debug: true
, check DSN, open browser console for SDK errors
Source maps not workingBuild in production mode (
npm run build
); verify
SENTRY_AUTH_TOKEN
is set
Minified stack tracesSource maps not uploading — check plugin config and auth token
instrument.ts
not running first
Verify it's the first import in entry file before React/app imports
React 19 errors not capturedConfirm
reactErrorHandler()
is passed to all three
createRoot
options
React <19 errors not capturedEnsure
<Sentry.ErrorBoundary>
wraps the component tree
Router transactions named
<unknown>
Add router integration matching your router version
tracePropagationTargets
not matching
Check regex escaping; default is
localhost
and your DSN origin only
Session replay not recordingConfirm
replayIntegration()
is in init; check
replaysSessionSampleRate
Redux actions not in breadcrumbsAdd
Sentry.createReduxEnhancer()
to store enhancers
Ad blockers dropping eventsSet
tunnel: "/sentry-tunnel"
and add server-side relay endpoint
High replay storage costsLower
replaysSessionSampleRate
; keep
replaysOnErrorSampleRate: 1.0
Profiling not workingVerify
Document-Policy: js-profiling
header is set on document responses
问题解决方案
事件未上报设置
debug: true
,检查DSN是否正确,查看浏览器控制台的SDK错误日志
Source Maps不生效以生产模式构建(
npm run build
);确认
SENTRY_AUTH_TOKEN
已正确配置
堆栈跟踪显示压缩代码Source Maps未上传 —— 检查插件配置和授权令牌
instrument.ts
未优先执行
确认它是入口文件中的第一个导入,早于React和应用代码
React 19错误未捕获确认
reactErrorHandler()
已传入
createRoot
的三个配置项
React <19错误未捕获确保
<Sentry.ErrorBoundary>
包裹了整个组件树
路由事务名称显示
<unknown>
添加与路由版本匹配的路由集成
tracePropagationTargets
不匹配
检查正则表达式转义;默认仅匹配
localhost
和DSN源地址
会话重放未录制确认
replayIntegration()
已在初始化中配置;检查
replaysSessionSampleRate
Redux操作未出现在面包屑中为Store增强器添加
Sentry.createReduxEnhancer()
广告拦截器阻止事件上报设置
tunnel: "/sentry-tunnel"
并添加服务器端中继端点
会话重放存储成本过高调低
replaysSessionSampleRate
;保持
replaysOnErrorSampleRate: 1.0
性能分析不生效确认文档响应头已设置
Document-Policy: js-profiling