sentry-tanstack-start-sdk

作者: sentry

完整的 Sentry SDK 設定,適用於 TanStack Start React。當被要求「將 Sentry 加入 TanStack Start」、「安裝 @sentry/tanstackstart-react」或設定錯誤…時使用。

npx skills add https://github.com/getsentry/sentry-for-ai --skill sentry-tanstack-start-sdk

All Skills > SDK Setup > 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.

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.


Phase 1: Detect

Run these commands to understand the project before making any recommendations:

# Detect TanStack Start / Router and existing Sentry
cat package.json | grep -E '"@tanstack/react-start"|"@tanstack/react-router"|"@sentry/tanstackstart-react"'

# Check if Sentry is already present
cat package.json | grep '"@sentry/'

# Detect key files used by the TanStack Start setup
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"

# Detect deployment hints in scripts
cat package.json | grep -E '"dev"|"build"|"start"|NODE_OPTIONS|--import'

# Detect logging libraries
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:

QuestionImpact
@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

Phase 2: Recommend

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?"


Phase 3: Guide

Install

npm install @sentry/tanstackstart-react --save

Configure Client-Side Sentry in src/router.tsx

Initialize Sentry inside the router factory and gate it to the browser:

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___",
      dataCollection: {
        // userInfo: false,
        // httpBodies: [],
      },

      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

Create instrument.server.mjs in project root:

import * as Sentry from "@sentry/tanstackstart-react";

Sentry.init({
  dsn: "___PUBLIC_DSN___",
  dataCollection: {
    // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
    // https://docs.sentry.io/platforms/javascript/guides/tanstackstart-react/configuration/options/#dataCollection
    // userInfo: false,
    // httpBodies: [],
  },
  enableLogs: true,
  tracesSampleRate: 1.0,
});

Configure Vite Plugin in vite.config.ts

sentryTanstackStart should be the last plugin:

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.

Instrument Server Entry Point in src/server.ts

Wrap the fetch handler with wrapFetchWithSentry:

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

These middleware capture server-side request and function errors:

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.

Runtime Startup Patterns

Choose one runtime method:

Runtime patternUse when...Notes
--import flagYou can control Node startup flagsPreferred for production monitoring
Direct import in src/server.tsHost restricts startup flags (for example serverless hosts)Limits instrumentation to native Node APIs

--import examples:

{
  "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):

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.mdAlways
Tracing${SKILL_ROOT}/references/tracing.mdRoute/API performance visibility needed
Session Replay${SKILL_ROOT}/references/session-replay.mdUser-facing app
Logs${SKILL_ROOT}/references/logging.mdStructured logs and correlation needed
User Feedback${SKILL_ROOT}/references/user-feedback.mdIn-app feedback collection needed
TanStack Start Features${SKILL_ROOT}/references/tanstackstart-features.mdServer entry, Vite plugin, source maps, runtime startup

For each feature: Read ${SKILL_ROOT}/references/<feature>.md, follow steps exactly, verify it works.


Configuration Reference

Key Sentry.init() Options

OptionTypeDefaultNotes
dsnstringRequired; SDK is disabled when empty
dataCollectionobjectconservative unless setFine-grained control over auto-collected categories (userInfo, cookies, httpHeaders, httpBodies, queryParams, genAI). When omitted, the SDK falls back to sendDefaultPii (default false). Passing the object — even {} — flips unset categories to their permissive defaults; opt out per category.
integrationsIntegration[]SDK defaultsInclude TanStack Router tracing, replay, feedback as needed
enableLogsbooleanfalseEnables Sentry.logger.* APIs
tracesSampleRatenumber1.0 in development, lower in production
replaysSessionSampleRatenumberFraction of all sessions recorded
replaysOnErrorSampleRatenumberFraction of error sessions recorded
tunnelstringOptional ad-blocker bypass endpoint
debugbooleanfalseSDK diagnostic logging

TanStack Start-Specific APIs

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

Verification

Trigger test events to confirm Sentry receives data.

Issues Test (Frontend)

<button
  type="button"
  onClick={() => {
    throw new Error("Sentry Test Error");
  }}
>
  Break the world
</button>

Tracing Test (Frontend + API Route)

<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>

Logs Test

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

Phase 4: Cross-Link

After completing TanStack Start setup, check whether a companion backend exists without Sentry:

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 servicessentry-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 configUse 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

來自 sentry 的更多技能

generate-frontend-forms
sentry
使用 Sentry 新表單系統建立表單的指南。適用於實作表單、表單欄位、驗證或自動儲存功能時使用。
official
sentry-snapshots-cocoa
sentry
完整的 Sentry Snapshots 設定,適用於 Apple/Cocoa 專案。當被要求「設定 SnapshotPreviews」、「設定 Apple 快照測試」、「上傳 Apple 快照至…」時使用。
official
architecture-review
sentry
員工級別的程式碼庫健康檢查。找出單體模組、靜默失敗、型別安全漏洞、測試覆蓋缺口,以及LLM友善性問題。
official
linear-type-labeler
sentry
根據每個問題的標題與描述內容,從 Sentry 工作區的標籤分類法中分類 Linear 問題,並套用對應的類型標籤。
official
sentry-flutter-sdk
sentry
完整的 Sentry SDK 設定,適用於 Flutter 和 Dart。當被要求「為 Flutter 加入 Sentry」、「安裝 sentry_flutter」、「在 Dart 中設定 Sentry」或設定錯誤…時使用。
official
sentry-svelte-sdk
sentry
完整的 Sentry SDK 設定,適用於 Svelte 和 SvelteKit。當被要求「將 Sentry 加入 Svelte」、「將 Sentry 加入 SvelteKit」、「安裝 @sentry/sveltekit」或進行設定時使用…
official
vercel-react-best-practices
sentry
來自 Vercel Engineering 的 React 與 Next.js 效能優化指南。此技能應在撰寫、審查或重構 React/Next.js… 時使用。
official
bump-size-limit
sentry
在 .size-limit.js 中提高大小限制,當 size-limit CI 檢查失敗時使用。適用於使用者提到大小限制失敗、套件大小檢查失敗、CI 大小…等情況。
official