sentry-react-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
All Skills > SDK Setup > React SDK
所有技能 > SDK配置 > React SDK

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 v5/v6/v7 non-framework navigation, Redux state, or component performance
If project is React Router Framework mode using
@sentry/react-router
, use
sentry-react-router-framework-sdk
instead of this skill.
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 v5/v6/v7非框架模式导航、Redux状态或组件性能
如果项目使用
@sentry/react-router
的React Router 框架模式,请使用
sentry-react-router-framework-sdk
而非本技能。
注意: 以下SDK版本和API基于编写时的Sentry官方文档(
@sentry/react
≥8.0.0)。 实施前请务必对照docs.sentry.io/platforms/javascript/guides/react/进行验证。

Phase 1: Detect

阶段1:项目检测

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 and framework mode hints

检测路由和框架模式线索

cat package.json | grep -E '"react-router-dom"|"react-router"|"@react-router/"|"@tanstack/react-router"|"@sentry/react-router"'
cat package.json | grep -E '"react-router-dom"|"react-router"|"@react-router/"|"@tanstack/react-router"|"@sentry/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 Framework mode indicators (`@sentry/react-router`, `@react-router/*`)? | Use `sentry-react-router-framework-sdk` |
| `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框架模式标识(`@sentry/react-router`、`@react-router/*`)? | 使用`sentry-react-router-framework-sdk` |
| 是否为`react-router-dom` v5 / v6 / v7? | 决定使用哪种路由集成方案 |
| 是否使用`@tanstack/react-router`? | 使用`tanstackRouterBrowserTracingIntegration()` |
| 是否使用Redux? | 推荐使用`createReduxEnhancer()` |
| 是否检测到Vite? | 通过`sentryVitePlugin`生成源映射 |
| 是否为CRA(`react-scripts`)? | 在CRACO中通过`@sentry/webpack-plugin`生成源映射 |
| 是否发现后端目录? | 触发阶段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 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 v5/v6/v7 non-framework detected → configure matching router integration (see Phase 3)
  • React Router Framework mode detected → switch to
    sentry-react-router-framework-sdk
  • 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 v5/v6/v7非框架模式 → 配置匹配的路由集成(见阶段3)
  • 检测到React Router框架模式 → 切换至
    sentry-react-router-framework-sdk
  • 检测到Redux → 为Redux store添加
    createReduxEnhancer()
  • 检测到Vite → 配置
    sentryVitePlugin
    生成源映射(对于可读堆栈跟踪至关重要)
建议话术:“我建议配置错误监控+链路追踪+会话重放。需要同时添加日志功能或性能剖析吗?”

Phase 3: Guide

阶段3:配置引导

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 (non-framework mode):
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)
传入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 — 带钩子的集成(无数据API的v6):
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)

源映射配置(强烈推荐)

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,
        }),
      ],
    },
  },
};
没有源映射的话,堆栈跟踪会显示压缩后的代码。配置构建插件自动上传源映射:
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、组件追踪、源映射、集成目录
对于每个功能:阅读
${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 SHA — 将错误与版本关联
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

阶段4:跨端关联建议

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
— 查看docs.sentry.io/platforms/java/
Node.js(Express、Fastify)使用
@sentry/node
— 查看docs.sentry.io/platforms/javascript/guides/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错误信息
源映射不生效以生产模式构建(
npm run build
);验证
SENTRY_AUTH_TOKEN
已正确设置
堆栈跟踪显示压缩代码源映射未上传 — 检查插件配置和授权令牌
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