sentry-react-router-framework-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAll Skills > SDK Setup > React Router Framework SDK
All Skills > SDK Setup > React Router Framework SDK
Sentry React Router Framework SDK
Sentry React Router Framework SDK
Opinionated wizard that scans your React Router Framework project and guides you through complete Sentry setup across client and server entry points.
一个预设配置的向导工具,可扫描你的React Router Framework项目,并引导你完成客户端和服务端入口点的完整Sentry设置。
Invoke This Skill When
何时调用此技能
- User asks to "add Sentry to React Router Framework" or "set up Sentry in React Router v7 framework mode"
- User wants to install or configure
@sentry/react-router - User uses React Router framework entry files (,
entry.client.tsx) and wants tracing/error captureentry.server.tsx - User asks about ,
reactRouterTracingIntegration,sentryOnError, or React Router wizard setupcreateSentryHandleRequest
Important: This SDK is currently beta. For React Router non-framework/data/declarative mode (v5/v6/v7), usewithsentry-react-sdkintegrations instead.@sentry/react
- 用户要求“为React Router Framework添加Sentry”或“在React Router v7框架模式下设置Sentry”
- 用户想要安装或配置
@sentry/react-router - 用户使用React Router框架入口文件(、
entry.client.tsx)并需要追踪/错误捕获功能entry.server.tsx - 用户询问、
reactRouterTracingIntegration、sentryOnError或React Router向导设置相关问题createSentryHandleRequest
重要提示: 此SDK目前处于beta阶段。 对于React Router非框架/数据/声明式模式(v5/v6/v7),请使用搭配sentry-react-sdk集成。@sentry/react
Phase 1: Detect
阶段1:检测
Run these commands to understand the project before making any recommendations:
bash
undefined在给出任何建议前,运行以下命令了解项目情况:
bash
undefinedDetect React Router Framework indicators and versions
Detect React Router Framework indicators and versions
cat package.json | grep -E '"react-router"|"@react-router/"|"react-router-dev"|"react-router-serve"'
cat package.json | grep -E '"react-router"|"@react-router/"|"react-router-dev"|"react-router-serve"'
Detect Sentry package choice
Detect Sentry package choice
cat package.json | grep -E '"@sentry/react-router"|"@sentry/react"|"@sentry/profiling-node"'
cat package.json | grep -E '"@sentry/react-router"|"@sentry/react"|"@sentry/profiling-node"'
Check entry point visibility and server instrumentation files
Check entry point visibility and server instrumentation files
ls entry.client.tsx entry.server.tsx instrument.server.mjs react-router.config.ts vite.config.ts 2>/dev/null
ls entry.client.tsx entry.server.tsx instrument.server.mjs react-router.config.ts vite.config.ts 2>/dev/null
Check if React Router files are still hidden (framework mode helper command available)
Check if React Router files are still hidden (framework mode helper command available)
cat package.json | grep -E '"reveal"|react-router'
cat package.json | grep -E '"reveal"|react-router'
Detect runtime startup scripts and import strategy
Detect runtime startup scripts and import strategy
cat package.json | grep -E '"dev"|"start"|NODE_OPTIONS|--import'
cat package.json | grep -E '"dev"|"start"|NODE_OPTIONS|--import'
Detect optional logging/profile-related dependencies
Detect optional logging/profile-related dependencies
cat package.json | grep -E '"pino"|"winston"|"@sentry/profiling-node"'
cat package.json | grep -E '"pino"|"winston"|"@sentry/profiling-node"'
Detect companion backend directories
Detect companion backend 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 |
|----------|--------|
| `@sentry/react-router` already installed? | Skip install and move to feature setup |
| Framework entry files exposed? | Need `npx react-router reveal` before manual config |
| Using `@sentry/react` instead? | This is likely non-framework routing; redirect to `sentry-react-sdk` |
| `react-router.config.ts` + Vite config present? | Source map upload and build-end hook setup path |
| `NODE_OPTIONS --import` available? | Preferred server instrumentation startup path |
| `@sentry/profiling-node` desired/available? | Enable server profiling integration |
| 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
**需要确定的信息:**
| 问题 | 影响 |
|----------|--------|
| 是否已安装`@sentry/react-router`? | 跳过安装步骤,直接进入功能设置 |
| 框架入口文件是否已暴露? | 需要先运行`npx react-router reveal`再进行手动配置 |
| 是否正在使用`@sentry/react`? | 这可能是非框架路由场景;请转向`sentry-react-sdk` |
| 是否存在`react-router.config.ts` + Vite配置? | 确定源码映射上传和构建结束钩子的设置路径 |
| 是否支持`NODE_OPTIONS --import`? | 这是服务端 instrumentation 启动的首选方式 |
| 是否需要/已安装`@sentry/profiling-node`? | 启用服务端性能分析集成 |
| 是否找到后端目录? | 触发阶段4的跨链路建议 |
---Phase 2: Recommend
阶段2:推荐
Present a concrete recommendation based on what you found. Do not ask open-ended questions — lead with a proposal:
Recommended (core coverage):
- ✅ Error Monitoring — always; captures client and server errors with framework hooks
- ✅ Tracing — recommended baseline in framework apps with client/server request flow
- ✅ Session Replay — recommended for user-facing applications
Optional (enhanced observability):
- ⚡ Profiling — server-side profiling with
@sentry/profiling-node - ⚡ Logs — structured ingestion and correlation
Sentry.logger.* - ⚡ User Feedback — in-app feedback widget/reporting flows
Recommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| Tracing | Usually yes in framework apps; route and request timing is high-value |
| Session Replay | User-facing product or difficult UX debugging |
| Profiling | Server performance investigations needed; Node runtime compatibility verified |
| Logs | Team wants log-search and trace correlation in Sentry |
| User Feedback | Product/support teams need direct in-app issue reports |
Propose: "I recommend Error Monitoring + Tracing + Session Replay first. Want me to also enable Profiling, Logs, and User Feedback?"
根据检测结果给出具体建议。不要提出开放式问题,直接给出方案:
推荐(核心覆盖):
- ✅ 错误监控 — 必选;通过框架钩子捕获客户端和服务端错误
- ✅ 链路追踪 — 框架应用中的推荐基线,适用于客户端/服务端请求流
- ✅ 会话重放 — 面向用户的应用推荐使用
可选(增强可观测性):
- ⚡ 性能分析 — 使用进行服务端性能分析
@sentry/profiling-node - ⚡ 日志 — 结构化数据采集与关联
Sentry.logger.* - ⚡ 用户反馈 — 应用内反馈组件/上报流程
推荐逻辑:
| 功能 | 推荐场景 |
|---|---|
| 错误监控 | 始终开启 — 不可或缺的基础功能 |
| 链路追踪 | 通常推荐开启 框架应用;路由和请求时序数据价值较高 |
| 会话重放 | 面向用户的产品或需要调试复杂UX场景 |
| 性能分析 | 需要排查服务端性能问题;已验证Node运行时兼容性 |
| 日志 | 团队需要在Sentry中进行日志搜索和追踪关联 |
| 用户反馈 | 产品/支持团队需要直接获取应用内问题报告 |
建议话术:"我建议先开启错误监控 + 链路追踪 + 会话重放。需要我同时启用性能分析、日志和用户反馈功能吗?"
Phase 3: Guide
阶段3:引导
Option 1: Wizard (Recommended)
选项1:向导工具(推荐)
You need to run this yourself — the wizard is interactive and may require browser login:bashnpx @sentry/wizard@latest -i reactRouterIt installs, exposes React Router entry files, creates instrumentation files, updates root error handling, configures source map upload, and adds verification examples.@sentry/react-routerOnce it finishes, continue at Verification.
If the user skips wizard setup, continue with manual setup below.
你需要自行运行此命令 — 向导是交互式的,可能需要浏览器登录:bashnpx @sentry/wizard@latest -i reactRouter它会安装、暴露React Router入口文件、创建instrumentation文件、更新根错误处理逻辑、配置源码映射上传,并添加验证示例。@sentry/react-router完成后,请继续查看验证部分。
如果用户跳过向导设置,请继续以下手动设置步骤。
Option 2: Manual Setup
选项2:手动设置
Install packages
安装依赖包
bash
npm install @sentry/react-router --saveIf profiling is needed:
bash
npm install @sentry/profiling-node --savebash
npm install @sentry/react-router --save如果需要性能分析功能:
bash
npm install @sentry/profiling-node --saveExpose framework entry files
暴露框架入口文件
bash
npx react-router revealbash
npx react-router revealConfigure client in entry.client.tsx
entry.client.tsx在entry.client.tsx
中配置客户端
entry.client.tsxtsx
import * as Sentry from "@sentry/react-router";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";
Sentry.init({
dsn: "___PUBLIC_DSN___",
sendDefaultPii: true,
integrations: [
Sentry.reactRouterTracingIntegration(),
Sentry.replayIntegration(),
Sentry.feedbackIntegration({ colorScheme: "system" }),
],
enableLogs: true,
tracesSampleRate: 1.0,
tracePropagationTargets: [/^\//, /^https:\/\/yourserver\.io\/api/],
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<HydratedRouter onError={Sentry.sentryOnError} />
</StrictMode>,
);
});tsx
import * as Sentry from "@sentry/react-router";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";
Sentry.init({
dsn: "___PUBLIC_DSN___",
sendDefaultPii: true,
integrations: [
Sentry.reactRouterTracingIntegration(),
Sentry.replayIntegration(),
Sentry.feedbackIntegration({ colorScheme: "system" }),
],
enableLogs: true,
tracesSampleRate: 1.0,
tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/],
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<HydratedRouter onError={Sentry.sentryOnError} />
</StrictMode>,
);
});Configure server in instrument.server.mjs
instrument.server.mjs在instrument.server.mjs
中配置服务端
instrument.server.mjsjavascript
import * as Sentry from "@sentry/react-router";
import { nodeProfilingIntegration } from "@sentry/profiling-node";
Sentry.init({
dsn: "___PUBLIC_DSN___",
sendDefaultPii: true,
enableLogs: true,
integrations: [nodeProfilingIntegration()],
tracesSampleRate: 1.0,
profileSessionSampleRate: 1.0,
});javascript
import * as Sentry from "@sentry/react-router";
import { nodeProfilingIntegration } from "@sentry/profiling-node";
Sentry.init({
dsn: "___PUBLIC_DSN___",
sendDefaultPii: true,
enableLogs: true,
integrations: [nodeProfilingIntegration()],
tracesSampleRate: 1.0,
profileSessionSampleRate: 1.0,
});Wrap server handlers in entry.server.tsx
entry.server.tsx在entry.server.tsx
中包装服务端处理器
entry.server.tsxtsx
import * as Sentry from "@sentry/react-router";
import { createReadableStreamFromReadable } from "@react-router/node";
import { renderToPipeableStream } from "react-dom/server";
import { ServerRouter } from "react-router";
const handleRequest = Sentry.createSentryHandleRequest({
ServerRouter,
renderToPipeableStream,
createReadableStreamFromReadable,
});
export default handleRequest;
export const handleError = Sentry.createSentryHandleError({
logErrors: false,
});For custom server logic, use , , and manual in your custom .
wrapSentryHandleRequestgetMetaTagTransformerSentry.captureExceptionhandleErrortsx
import * as Sentry from "@sentry/react-router";
import { createReadableStreamFromReadable } from "@react-router/node";
import { renderToPipeableStream } from "react-dom/server";
import { ServerRouter } from "react-router";
const handleRequest = Sentry.createSentryHandleRequest({
ServerRouter,
renderToPipeableStream,
createReadableStreamFromReadable,
});
export default handleRequest;
export const handleError = Sentry.createSentryHandleError({
logErrors: false,
});对于自定义服务端逻辑,请在自定义中使用、和手动。
handleErrorwrapSentryHandleRequestgetMetaTagTransformerSentry.captureExceptionLoad server instrumentation on startup
在启动时加载服务端instrumentation
Prefer :
NODE_OPTIONS --importjson
{
"scripts": {
"dev": "NODE_OPTIONS='--import ./instrument.server.mjs' react-router dev",
"start": "NODE_OPTIONS='--import ./instrument.server.mjs' react-router-serve ./build/server/index.js"
}
}Fallback for platforms where runtime flags are restricted:
tsx
import "./instrument.server.mjs";This direct-import method can result in incomplete auto-instrumentation compared to .
--import优先使用方式:
NODE_OPTIONS --importjson
{
"scripts": {
"dev": "NODE_OPTIONS='--import ./instrument.server.mjs' react-router dev",
"start": "NODE_OPTIONS='--import ./instrument.server.mjs' react-router-serve ./build/server/index.js"
}
}对于限制运行时标志的平台,可使用备选方案:
tsx
import "./instrument.server.mjs";与方式相比,这种直接导入方法可能导致自动instrumentation不完整。
--importConfigure source maps
配置源码映射
vite.config.tstypescript
import { reactRouter } from "@react-router/dev/vite";
import {
sentryReactRouter,
type SentryReactRouterBuildOptions,
} from "@sentry/react-router";
import { defineConfig } from "vite";
const sentryConfig: SentryReactRouterBuildOptions = {
org: "___ORG_SLUG___",
project: "___PROJECT_SLUG___",
authToken: process.env.SENTRY_AUTH_TOKEN,
};
export default defineConfig((config) => {
return {
plugins: [reactRouter(), sentryReactRouter(sentryConfig, config)],
};
});react-router.config.tstypescript
import type { Config } from "@react-router/dev/config";
import { sentryOnBuildEnd } from "@sentry/react-router";
export default {
ssr: true,
buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => {
await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest });
},
} satisfies Config;vite.config.tstypescript
import { reactRouter } from "@react-router/dev/vite";
import {
sentryReactRouter,
type SentryReactRouterBuildOptions,
} from "@sentry/react-router";
import { defineConfig } from "vite";
const sentryConfig: SentryReactRouterBuildOptions = {
org: "___ORG_SLUG___",
project: "___PROJECT_SLUG___",
authToken: process.env.SENTRY_AUTH_TOKEN,
};
export default defineConfig((config) => {
return {
plugins: [reactRouter(), sentryReactRouter(sentryConfig, config)],
};
});react-router.config.tstypescript
import type { Config } from "@react-router/dev/config";
import { sentryOnBuildEnd } from "@sentry/react-router";
export default {
ssr: true,
buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => {
await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest });
},
} satisfies Config;For Each Agreed Feature
针对每个确认的功能
Walk through features one at a time. Load the reference file, follow steps exactly, and verify before moving on:
| Feature | Reference | Load when... |
|---|---|---|
| Error Monitoring | | Always |
| Tracing | | Route/request performance visibility needed |
| Profiling | | Server performance analysis needed |
| Session Replay | | User-facing app |
| Logs | | Structured logs/correlation needed |
| User Feedback | | In-app feedback flows needed |
| Framework Features | | Entry files, wrappers, source maps, startup import strategy |
For each feature: , follow steps exactly, verify it works.
Read ${SKILL_ROOT}/references/<feature>.md逐个功能进行配置。加载参考文件,严格按照步骤操作,并在进行下一步前验证功能正常:
| 功能 | 参考文件 | 加载时机 |
|---|---|---|
| 错误监控 | | 始终加载 |
| 链路追踪 | | 需要路由/请求性能可见性时 |
| 性能分析 | | 需要分析服务端性能时 |
| 会话重放 | | 面向用户的应用 |
| 日志 | | 需要结构化日志/关联时 |
| 用户反馈 | | 需要应用内反馈流程时 |
| 框架功能 | | 涉及入口文件、包装器、源码映射、启动导入策略时 |
对于每个功能:,严格按照步骤操作,验证功能正常。
读取${SKILL_ROOT}/references/<feature>.mdConfiguration Reference
配置参考
Key Sentry.init()
options
Sentry.init()Sentry.init()
关键选项
Sentry.init()| Option | Type | Default | Notes |
|---|---|---|---|
| | — | Required; SDK disabled when empty |
| | | Includes headers/IP-derived user context |
| | SDK defaults | Add tracing/replay/feedback/profiling integrations |
| | | Enables |
| | — | Usually |
| `(string | RegExp)[]` | SDK defaults |
| | — | Fraction of all sessions recorded |
| | — | Fraction of error sessions recorded |
| | — | Fraction of transactions profiled (server profiling) |
| | — | Optional ad-blocker bypass endpoint |
| | | Verbose SDK diagnostics |
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | — | 必填;为空时SDK将禁用 |
| | | 包含请求头/基于IP的用户上下文 |
| | SDK默认值 | 添加追踪/重放/反馈/性能分析集成 |
| | | 启用 |
| | — | 测试环境通常设为 |
| `(string | RegExp)[]` | SDK默认值 |
| | — | 录制的会话比例 |
| | — | 发生错误的会话录制比例 |
| | — | 进行性能分析的事务比例(服务端性能分析) |
| | — | 可选的广告拦截器绕过端点 |
| | | 启用SDK详细诊断日志 |
Framework-specific APIs
框架专属API
| API | Purpose |
|---|---|
| Client-side tracing integration for framework mode |
| Hooks into React Router |
| Server request wrapper for framework entry server |
| Server error handler wrapper |
| Manual wrapping for server loaders/actions |
| Vite plugin for source maps/build integration |
| React Router build-end hook for source map processing |
| API | 用途 |
|---|---|
| 框架模式下的客户端链路追踪集成 |
| 接入React Router |
| 框架服务端入口的请求包装器 |
| 服务端错误处理器包装器 |
| 手动包装服务端加载器/动作 |
| 用于源码映射/构建集成的Vite插件 |
| 用于源码映射处理的React Router构建结束钩子 |
Verification
验证
Wizard-generated path
向导生成路径
If wizard examples were generated, open and trigger test actions.
/sentry-example-page如果向导生成了示例页面,打开并触发测试操作。
/sentry-example-pageManual error test
手动错误测试
tsx
export async function loader() {
throw new Error("My first Sentry error!");
}tsx
export async function loader() {
throw new Error("My first Sentry error!");
}Manual tracing test
手动追踪测试
tsx
import * as Sentry from "@sentry/react-router";
export async function loader() {
return Sentry.startSpan(
{ op: "test", name: "My First Test Transaction" },
() => {
throw new Error("My first Sentry error!");
},
);
}tsx
import * as Sentry from "@sentry/react-router";
export async function loader() {
return Sentry.startSpan(
{ op: "test", name: "My First Test Transaction" },
() => {
throw new Error("My first Sentry error!");
},
);
}Logs test
日志测试
javascript
Sentry.logger.info("User example action completed");
Sentry.logger.warn("Slow operation detected", { operation: "data_fetch", duration: 3500 });
Sentry.logger.error("Validation failed", { field: "email", reason: "Invalid email" });Confirm in Sentry:
- Issues: errors appear
- Traces: transaction/span data appears
- Profiles: profiles appear when profiling enabled
- Replays: replay entries appear when enabled
- Logs: log events appear when
enableLogs: true - User Feedback: submissions appear when feedback enabled
javascript
Sentry.logger.info("User example action completed");
Sentry.logger.warn("Slow operation detected", { operation: "data_fetch", duration: 3500 });
Sentry.logger.error("Validation failed", { field: "email", reason: "Invalid email" });在Sentry中确认:
- 问题:错误已显示
- 追踪:事务/跨度数据已显示
- 性能分析:启用性能分析后,性能分析数据已显示
- 会话重放:启用后,会话重放条目已显示
- 日志:开启后,日志事件已显示
enableLogs: true - 用户反馈:启用后,反馈提交内容已显示
Phase 4: Cross-Link
阶段4:跨链路关联
After completing React Router Framework setup:
- Check whether the app is actually non-framework routing (v5/v6/v7 data/declarative with ).
@sentry/react - If yes, redirect to for non-framework routing integrations.
sentry-react-sdk
Then check companion backend coverage:
bash
ls ../backend ../server ../api ../go ../python 2>/dev/null
cat ../go.mod ../requirements.txt ../pyproject.toml ../Gemfile ../pom.xml 2>/dev/null | head -5| Backend detected | Suggest skill |
|---|---|
| Go | |
| Python | |
| Ruby | |
| Node backend services | |
| Java services | Use |
完成React Router Framework设置后:
- 检查应用是否实际为非框架路由(v5/v6/v7数据/声明式模式搭配)。
@sentry/react - 如果是,转向进行非框架路由集成。
sentry-react-sdk
然后检查配套后端覆盖情况:
bash
ls ../backend ../server ../api ../go ../python 2>/dev/null
cat ../go.mod ../requirements.txt ../pyproject.toml ../Gemfile ../pom.xml 2>/dev/null | head -5| 检测到的后端 | 推荐技能 |
|---|---|
| Go | |
| Python | |
| Ruby | |
| Node后端服务 | |
| Java服务 | 使用 |
Troubleshooting
故障排查
| Issue | Solution |
|---|---|
| Run |
| Client errors missing | Ensure |
| Server errors missing | Use |
| Custom server handlers bypass Sentry | Use |
| Source maps not uploaded | Verify |
| Load env vars in config or use |
| Incomplete server auto-instrumentation | Prefer |
| Profiling data missing | Confirm |
| Running unsupported Node auto-instrumentation version | Use instrumentation API/manual wrappers as documented |
Non-framework app configured with | Switch to |
| 问题 | 解决方案 |
|---|---|
缺少 | 先运行 |
| 客户端错误未上报 | 确保 |
| 服务端错误未上报 | 使用 |
| 自定义服务端处理器绕过Sentry | 在自定义 |
| 源码映射未上传 | 验证 |
Vite配置中 | 在配置中加载环境变量或使用 |
| 服务端自动instrumentation不完整 | 优先使用 |
| 性能分析数据缺失 | 确认已安装 |
| 运行不支持的Node自动instrumentation版本 | 按照文档使用instrumentation API/手动包装器 |
非框架应用使用 | 切换为 |
| ", |