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添加Sentry」或在TanStack Start React应用中「配置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/路由及已有的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

安装SDK

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
包裹fetch处理器:
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(...)
服务器请求追踪 + 捕获fetch处理器错误
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("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 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
直接导入方式缺失库链路数据尽可能使用
--import
启动方式;直接导入仅支持原生Node埋点
SSR渲染异常未自动捕获在错误边界/降级处理器中手动调用
Sentry.captureException
捕获