sentry-tanstack-start-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
All Skills > SDK Setup > TanStack Start React SDK
所有技能 > SDK 安装 > TanStack Start React SDK

Sentry TanStack Start React SDK

Sentry TanStack Start React SDK

Opinionated wizard that scans your TanStack Start React project and guides you through complete Sentry setup for browser and server runtimes.
一款预设配置的向导工具,可扫描你的 TanStack Start React 项目,并引导你完成浏览器和服务器运行时的完整 Sentry 配置。

Invoke This Skill When

何时调用此技能

  • User asks to "add Sentry to TanStack Start" or "set up Sentry" in a TanStack Start React app
  • User wants to install or configure
    @sentry/tanstackstart-react
  • User wants error monitoring, tracing, session replay, logs, or user feedback for TanStack Start React
  • User asks about
    sentryTanstackStart
    ,
    wrapFetchWithSentry
    ,
    instrument.server.mjs
    , or TanStack Start middleware instrumentation
Note: This SDK is currently alpha and documented as compatible with TanStack Start
1.0 RC
. Always verify against docs.sentry.io/platforms/javascript/guides/tanstackstart-react/ before implementing.

  • 用户要求在 TanStack Start React 应用中“添加 Sentry”或“配置 Sentry”
  • 用户想要安装或配置
    @sentry/tanstackstart-react
  • 用户想要为 TanStack Start React 配置错误监控、链路追踪、会话重放、日志或用户反馈
  • 用户询问
    sentryTanstackStart
    wrapFetchWithSentry
    instrument.server.mjs
    或 TanStack Start 中间件埋点相关内容
注意: 此 SDK 当前处于 alpha 阶段,文档标注兼容 TanStack Start
1.0 RC
。 实施前请务必参考 docs.sentry.io/platforms/javascript/guides/tanstackstart-react/ 进行验证。

Phase 1: Detect

阶段1:检测

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

Detect TanStack Start / Router and existing Sentry

检测 TanStack Start / Router 和已有的 Sentry

cat package.json | grep -E '"@tanstack/react-start"|"@tanstack/react-router"|"@sentry/tanstackstart-react"'
cat package.json | grep -E '"@tanstack/react-start"|"@tanstack/react-router"|"@sentry/tanstackstart-react"'

Check if Sentry is already present

检查是否已存在 Sentry

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

Detect key files used by the TanStack Start setup

检测 TanStack Start 配置所需的关键文件

ls src/router.tsx src/start.ts src/server.ts instrument.server.mjs vite.config.ts vite.config.js 2>/dev/null
ls src/router.tsx src/start.ts src/server.ts instrument.server.mjs vite.config.ts vite.config.js 2>/dev/null

Check whether source map upload credentials are configured

检查是否配置了源码映射上传凭证

cat .env .env.local .env.sentry-build-plugin 2>/dev/null | grep "SENTRY_AUTH_TOKEN"
cat .env .env.local .env.sentry-build-plugin 2>/dev/null | grep "SENTRY_AUTH_TOKEN"

Detect deployment hints in scripts

检测脚本中的部署提示

cat package.json | grep -E '"dev"|"build"|"start"|NODE_OPTIONS|--import'
cat package.json | grep -E '"dev"|"build"|"start"|NODE_OPTIONS|--import'

Detect logging libraries

检测日志库

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

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 |
|----------|--------|
| `@tanstack/react-start` present? | Confirms this skill is the right setup path |
| `@sentry/tanstackstart-react` already installed? | Skip install and go to feature tuning |
| `src/router.tsx` exists? | Client-side `Sentry.init` placement |
| `src/start.ts` exists? | Global middleware setup for server-side errors |
| `src/server.ts` exists? | Server entry instrumentation placement |
| `instrument.server.mjs` exists? | Runtime startup instrumentation path |
| `vite.config.ts` exists? | Add `sentryTanstackStart` plugin and source maps |
| `SENTRY_AUTH_TOKEN` configured? | Source map upload readiness |
| 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

**需要确定的内容:**

| 问题 | 影响 |
|----------|--------|
| 是否存在 `@tanstack/react-start`? | 确认此技能是正确的配置路径 |
| 是否已安装 `@sentry/tanstackstart-react`? | 跳过安装步骤,直接进行功能调优 |
| 是否存在 `src/router.tsx`? | 决定客户端 `Sentry.init` 的放置位置 |
| 是否存在 `src/start.ts`? | 决定服务器端错误的全局中间件配置方式 |
| 是否存在 `src/server.ts`? | 决定服务器入口埋点的放置位置 |
| 是否存在 `instrument.server.mjs`? | 决定运行时启动埋点的路径 |
| 是否存在 `vite.config.ts`? | 需要添加 `sentryTanstackStart` 插件和源码映射配置 |
| 是否已配置 `SENTRY_AUTH_TOKEN`? | 决定源码映射上传是否就绪 |
| 是否找到后端目录? | 触发阶段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 unhandled client and server errors
  • Tracing — high-value for request and route timing across browser and server
  • Session Replay — recommended for user-facing apps
Optional (enhanced observability):
  • Logs — recommend when structured log search and log-to-trace correlation are needed
  • User Feedback — recommend when product teams want in-app issue reports
Recommendation logic:
FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline
TracingUsually yes for TanStack Start; route + fetch instrumentation gives immediate value
Session ReplayUser-facing app, login flows, checkout flows, or hard-to-reproduce UX bugs
LogsExisting logging strategy, support workflow, or trace/log correlation needs
User FeedbackTeam wants direct user reports without leaving the app
Propose: "I recommend Error Monitoring + Tracing + Session Replay. Want me to also enable Logs and User Feedback?"

根据检测结果给出具体建议,不要提出开放式问题,直接给出方案:
推荐(核心覆盖):
  • 错误监控 — 必选;捕获客户端和服务器端未处理的错误
  • 链路追踪 — 高价值功能,可追踪浏览器和服务器端的请求及路由耗时
  • 会话重放 — 面向用户的应用推荐配置
可选(增强可观测性):
  • 日志 — 当需要结构化日志搜索及日志与链路关联时推荐配置
  • 用户反馈 — 当产品团队需要收集应用内问题报告时推荐配置
推荐逻辑:
功能推荐场景
错误监控始终开启 — 不可或缺的基础功能
链路追踪TanStack Start 应用通常建议开启;路由 + 请求埋点可立即发挥价值
会话重放面向用户的应用、登录流程、结账流程,或难以复现的 UX 问题场景
日志已有日志策略、支持工作流,或需要日志与链路关联的场景
用户反馈团队希望在不离开应用的情况下收集用户直接反馈的场景
建议话术:“我推荐配置错误监控 + 链路追踪 + 会话重放。需要同时开启日志和用户反馈功能吗?”

Phase 3: Guide

阶段3:引导

Install

安装

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

Configure Client-Side Sentry in
src/router.tsx

src/router.tsx
中配置客户端 Sentry

Initialize Sentry inside the router factory and gate it to the browser:
tsx
import * as Sentry from "@sentry/tanstackstart-react";
import { createRouter } from "@tanstack/react-router";

export const getRouter = () => {
  const router = createRouter();

  if (!router.isServer) {
    Sentry.init({
      dsn: "___PUBLIC_DSN___",
      sendDefaultPii: true,

      integrations: [
        Sentry.tanstackRouterBrowserTracingIntegration(router),
        Sentry.replayIntegration(),
        Sentry.feedbackIntegration({
          colorScheme: "system",
        }),
      ],

      enableLogs: true,
      tracesSampleRate: 1.0,
      replaysSessionSampleRate: 0.1,
      replaysOnErrorSampleRate: 1.0,
    });
  }

  return router;
};
在路由工厂内初始化 Sentry,并限制仅在浏览器环境运行:
tsx
import * as Sentry from "@sentry/tanstackstart-react";
import { createRouter } from "@tanstack/react-router";

export const getRouter = () => {
  const router = createRouter();

  if (!router.isServer) {
    Sentry.init({
      dsn: "___PUBLIC_DSN___",
      sendDefaultPii: true,

      integrations: [
        Sentry.tanstackRouterBrowserTracingIntegration(router),
        Sentry.replayIntegration(),
        Sentry.feedbackIntegration({
          colorScheme: "system",
        }),
      ],

      enableLogs: true,
      tracesSampleRate: 1.0,
      replaysSessionSampleRate: 0.1,
      replaysOnErrorSampleRate: 1.0,
    });
  }

  return router;
};

Configure Server-Side Sentry in
instrument.server.mjs

instrument.server.mjs
中配置服务器端 Sentry

Create
instrument.server.mjs
in project root:
javascript
import * as Sentry from "@sentry/tanstackstart-react";

Sentry.init({
  dsn: "___PUBLIC_DSN___",
  sendDefaultPii: true,
  enableLogs: true,
  tracesSampleRate: 1.0,
});
在项目根目录创建
instrument.server.mjs
javascript
import * as Sentry from "@sentry/tanstackstart-react";

Sentry.init({
  dsn: "___PUBLIC_DSN___",
  sendDefaultPii: true,
  enableLogs: true,
  tracesSampleRate: 1.0,
});

Configure Vite Plugin in
vite.config.ts

vite.config.ts
中配置 Vite 插件

sentryTanstackStart
should be the last plugin:
typescript
import { defineConfig } from "vite";
import { sentryTanstackStart } from "@sentry/tanstackstart-react/vite";
import { tanstackStart } from "@tanstack/react-start/plugin/vite";

export default defineConfig({
  plugins: [
    tanstackStart(),
    sentryTanstackStart({
      org: "___ORG_SLUG___",
      project: "___PROJECT_SLUG___",
      authToken: process.env.SENTRY_AUTH_TOKEN,
    }),
  ],
});
If the token is stored in
.env
, load it with
loadEnv
in the Vite config before passing it to the plugin.
sentryTanstackStart
应作为最后一个插件:
typescript
import { defineConfig } from "vite";
import { sentryTanstackStart } from "@sentry/tanstackstart-react/vite";
import { tanstackStart } from "@tanstack/react-start/plugin/vite";

export default defineConfig({
  plugins: [
    tanstackStart(),
    sentryTanstackStart({
      org: "___ORG_SLUG___",
      project: "___PROJECT_SLUG___",
      authToken: process.env.SENTRY_AUTH_TOKEN,
    }),
  ],
});
如果凭证存储在
.env
中,需在 Vite 配置中使用
loadEnv
加载后再传入插件。

Instrument Server Entry Point in
src/server.ts

src/server.ts
中埋点服务器入口

Wrap the fetch handler with
wrapFetchWithSentry
:
typescript
import { wrapFetchWithSentry } from "@sentry/tanstackstart-react";
import handler, { createServerEntry } from "@tanstack/react-start/server-entry";

export default createServerEntry(
  wrapFetchWithSentry({
    fetch(request: Request) {
      return handler.fetch(request);
    },
  }),
);
使用
wrapFetchWithSentry
包裹请求处理函数:
typescript
import { wrapFetchWithSentry } from "@sentry/tanstackstart-react";
import handler, { createServerEntry } from "@tanstack/react-start/server-entry";

export default createServerEntry(
  wrapFetchWithSentry({
    fetch(request: Request) {
      return handler.fetch(request);
    },
  }),
);

Add Global Server Middleware in
src/start.ts

src/start.ts
中添加全局服务器中间件

These middleware capture server-side request and function errors:
tsx
import {
  sentryGlobalFunctionMiddleware,
  sentryGlobalRequestMiddleware,
} from "@sentry/tanstackstart-react";
import { createStart } from "@tanstack/react-start";

export const startInstance = createStart(() => {
  return {
    requestMiddleware: [sentryGlobalRequestMiddleware],
    functionMiddleware: [sentryGlobalFunctionMiddleware],
  };
});
Sentry middleware should be first in each array.
这些中间件可捕获服务器端请求和函数错误:
tsx
import {
  sentryGlobalFunctionMiddleware,
  sentryGlobalRequestMiddleware,
} from "@sentry/tanstackstart-react";
import { createStart } from "@tanstack/react-start";

export const startInstance = createStart(() => {
  return {
    requestMiddleware: [sentryGlobalRequestMiddleware],
    functionMiddleware: [sentryGlobalFunctionMiddleware],
  };
});
Sentry 中间件应放在每个数组的首位。

Runtime Startup Patterns

运行时启动模式

Choose one runtime method:
Runtime patternUse when...Notes
--import
flag
You can control Node startup flagsPreferred for production monitoring
Direct import in
src/server.ts
Host restricts startup flags (for example serverless hosts)Limits instrumentation to native Node APIs
--import
examples:
json
{
  "scripts": {
    "dev": "NODE_OPTIONS='--import ./instrument.server.mjs' vite dev --port 3000",
    "build": "vite build && cp instrument.server.mjs .output/server",
    "start": "node --import ./.output/server/instrument.server.mjs .output/server/index.mjs"
  }
}
Direct import fallback (top of
src/server.ts
):
typescript
import "../instrument.server.mjs";
选择以下一种运行时方式:
运行时模式适用场景说明
--import
标志
可控制 Node 启动标志时生产环境监控的首选方式
src/server.ts
中直接导入
主机限制启动标志(如无服务器主机)仅支持原生 Node API 埋点
--import
示例:
json
{
  "scripts": {
    "dev": "NODE_OPTIONS='--import ./instrument.server.mjs' vite dev --port 3000",
    "build": "vite build && cp instrument.server.mjs .output/server",
    "start": "node --import ./.output/server/instrument.server.mjs .output/server/index.mjs"
  }
}
直接导入降级方案(放在
src/server.ts
顶部):
typescript
import "../instrument.server.mjs";

For Each Agreed Feature

针对每个确认的功能

Walk through features one at a time. Load the reference file, follow steps exactly, and verify before moving on:
FeatureReferenceLoad when...
Error Monitoring
${SKILL_ROOT}/references/error-monitoring.md
Always
Tracing
${SKILL_ROOT}/references/tracing.md
Route/API performance visibility needed
Session Replay
${SKILL_ROOT}/references/session-replay.md
User-facing app
Logs
${SKILL_ROOT}/references/logging.md
Structured logs and correlation needed
User Feedback
${SKILL_ROOT}/references/user-feedback.md
In-app feedback collection needed
TanStack Start Features
${SKILL_ROOT}/references/tanstackstart-features.md
Server entry, Vite plugin, source maps, runtime startup
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/user-feedback.md
需要收集应用内反馈时
TanStack Start 功能
${SKILL_ROOT}/references/tanstackstart-features.md
服务器入口、Vite 插件、源码映射、运行时启动配置
针对每个功能:读取
${SKILL_ROOT}/references/<feature>.md
,严格遵循步骤,验证功能正常运行。

Configuration Reference

配置参考

Key
Sentry.init()
Options

Sentry.init()
关键选项

OptionTypeDefaultNotes
dsn
string
Required; SDK is disabled when empty
sendDefaultPii
boolean
false
Sends request headers and IP-derived user context
integrations
Integration[]
SDK defaultsInclude TanStack Router tracing, replay, feedback as needed
enableLogs
boolean
false
Enables
Sentry.logger.*
APIs
tracesSampleRate
number
1.0
in development, lower in production
replaysSessionSampleRate
number
Fraction of all sessions recorded
replaysOnErrorSampleRate
number
Fraction of error sessions recorded
tunnel
string
Optional ad-blocker bypass endpoint
debug
boolean
false
SDK diagnostic logging
选项类型默认值说明
dsn
string
必填;为空时 SDK 会禁用
sendDefaultPii
boolean
false
发送请求头和基于 IP 的用户上下文
integrations
Integration[]
SDK 默认值根据需要包含 TanStack Router 追踪、会话重放、用户反馈等集成
enableLogs
boolean
false
启用
Sentry.logger.*
API
tracesSampleRate
number
开发环境设为
1.0
,生产环境可降低
replaysSessionSampleRate
number
录制的会话占比
replaysOnErrorSampleRate
number
发生错误的会话录制占比
tunnel
string
可选的广告拦截器绕过端点
debug
boolean
false
SDK 诊断日志

TanStack Start-Specific APIs

TanStack Start 专属 API

APIPurpose
tanstackRouterBrowserTracingIntegration(router)
Browser navigation tracing
wrapFetchWithSentry(...)
Server request tracing + error capture on fetch handler
sentryGlobalRequestMiddleware
Captures request-level server errors
sentryGlobalFunctionMiddleware
Captures server function errors
sentryTanstackStart({...})
Vite plugin for source maps and middleware instrumentation

API用途
tanstackRouterBrowserTracingIntegration(router)
浏览器导航追踪
wrapFetchWithSentry(...)
服务器请求追踪 + 请求处理函数的错误捕获
sentryGlobalRequestMiddleware
捕获服务器端请求级错误
sentryGlobalFunctionMiddleware
捕获服务器端函数错误
sentryTanstackStart({...})
用于源码映射和中间件埋点的 Vite 插件

Verification

验证

Trigger test events to confirm Sentry receives data.
触发测试事件,确认 Sentry 能接收数据。

Issues Test (Frontend)

问题测试(前端)

tsx
<button
  type="button"
  onClick={() => {
    throw new Error("Sentry Test Error");
  }}
>
  Break the world
</button>
tsx
<button
  type="button"
  onClick={() => {
    throw new Error("Sentry Test Error");
  }}
>
  触发测试错误
</button>

Tracing Test (Frontend + API Route)

链路追踪测试(前端 + API 路由)

tsx
<button
  type="button"
  onClick={async () => {
    await Sentry.startSpan({ name: "Example Frontend Span", op: "test" }, async () => {
      const res = await fetch("/api/sentry-example");
      if (!res.ok) {
        throw new Error("Sentry Example Frontend Error");
      }
    });
  }}
>
  Break the world
</button>
tsx
<button
  type="button"
  onClick={async () => {
    await Sentry.startSpan({ name: "Example Frontend Span", op: "test" }, async () => {
      const res = await fetch("/api/sentry-example");
      if (!res.ok) {
        throw new Error("Sentry Example Frontend Error");
      }
    });
  }}
>
  触发测试链路
</button>

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: frontend/server errors appear
  • Traces: browser and server spans appear
  • Replays: session replay appears when enabled
  • Logs: log lines appear when
    enableLogs: true
  • User Feedback: submissions appear when feedback integration is enabled

javascript
Sentry.logger.info("用户示例操作完成");
Sentry.logger.warn("检测到慢操作", { operation: "data_fetch", duration: 3500 });
Sentry.logger.error("验证失败", { field: "email", reason: "无效邮箱" });
在 Sentry 中确认:
  • 问题:前端/服务器端错误已显示
  • 链路追踪:浏览器和服务器端的 span 已显示
  • 会话重放:开启后会话重放已生成
  • 日志:开启
    enableLogs: true
    后日志行已显示
  • 用户反馈:开启反馈集成后提交的反馈已显示

Phase 4: Cross-Link

阶段4:跨服务关联

After completing TanStack Start setup, check whether a companion backend exists without Sentry:
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
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
docs
Node.js backend services
sentry-node-sdk

完成 TanStack Start 配置后,检查是否存在未配置 Sentry 的关联后端:
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
如果存在未配置 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
文档
Node.js 后端服务
sentry-node-sdk

Troubleshooting

故障排查

IssueSolution
Events not appearingSet
debug: true
, verify DSN, and ensure client/server init files both run
No server tracesConfirm
src/server.ts
uses
wrapFetchWithSentry
and runtime loads
instrument.server.mjs
Server errors missing from route handlersEnsure
sentryGlobalRequestMiddleware
and
sentryGlobalFunctionMiddleware
are first in arrays
Source maps not resolvingVerify
SENTRY_AUTH_TOKEN
,
org
, and
project
in
sentryTanstackStart
config
SENTRY_AUTH_TOKEN
undefined in Vite config
Use
loadEnv(mode, process.cwd(), "")
or
.env.sentry-build-plugin
Replay not recordingEnsure
replayIntegration()
is in
integrations
and sample rates are non-zero
Feedback widget not visibleConfirm
feedbackIntegration()
is configured and check CSS z-index conflicts
Logs missing in SentrySet
enableLogs: true
and use
Sentry.logger.*
APIs
Direct-import setup misses library spansPrefer
--import
startup when possible; direct import supports native Node instrumentation only
SSR rendering exceptions not auto-capturedCapture manually with
Sentry.captureException
in error boundaries / fallback handlers
问题解决方案
事件未显示设置
debug: true
,验证 DSN,确保客户端/服务器端初始化文件均已运行
无服务器端链路追踪确认
src/server.ts
使用了
wrapFetchWithSentry
,且运行时加载了
instrument.server.mjs
路由处理器中的服务器端错误未捕获确保
sentryGlobalRequestMiddleware
sentryGlobalFunctionMiddleware
位于数组首位
源码映射未解析验证
sentryTanstackStart
配置中的
SENTRY_AUTH_TOKEN
org
project
Vite 配置中
SENTRY_AUTH_TOKEN
未定义
使用
loadEnv(mode, process.cwd(), "")
.env.sentry-build-plugin
会话重放未录制确保
replayIntegration()
已加入
integrations
,且采样率不为0
反馈组件不可见确认
feedbackIntegration()
已配置,并检查 CSS z-index 冲突
Sentry 中无日志设置
enableLogs: true
并使用
Sentry.logger.*
API
直接导入配置缺失库 span尽可能使用
--import
启动方式;直接导入仅支持原生 Node 埋点
SSR 渲染异常未自动捕获在错误边界/降级处理函数中手动调用
Sentry.captureException