sentry-react-sdk
Original:🇺🇸 English
Not Translated
Full Sentry SDK setup for React. Use when asked to "add Sentry to React", "install @sentry/react", or configure error monitoring, tracing, session replay, profiling, or logging for React applications. Supports React 16+, React Router v5-v7, TanStack Router, Redux, Vite, and webpack.
2installs
Sourcegetsentry/sentry-for-ai
Added on
NPX Install
npx skill4agent add getsentry/sentry-for-ai sentry-react-sdkSKILL.md Content
All Skills > SDK Setup > React SDK
Sentry React SDK
Opinionated wizard that scans your React project and guides you through complete Sentry setup.
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 , React Sentry SDK, or Sentry error boundaries
@sentry/react - User wants to monitor React Router navigation, Redux state, or component performance
Note: SDK versions and APIs below reflect current Sentry docs at time of writing (≥8.0.0). Always verify against docs.sentry.io/platforms/javascript/guides/react/ before implementing.@sentry/react
Phase 1: Detect
Run these commands to understand the project before making any recommendations:
bash
# Detect React version
cat package.json | grep -E '"react"|"react-dom"'
# Check for existing Sentry
cat package.json | grep '"@sentry/'
# Detect router
cat package.json | grep -E '"react-router-dom"|"@tanstack/react-router"'
# Detect state management
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"'
# Detect logging libraries
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 -3What to determine:
| Question | Impact |
|---|---|
| React 19+? | Use |
| React <19? | Use |
| Skip install, go straight to feature config |
| Determines which router integration to use |
| Use |
| Redux in use? | Recommend |
| Vite detected? | Source maps via |
CRA ( | Source maps via |
| Backend directory found? | Trigger Phase 4 cross-link suggestion |
Phase 2: Recommend
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 ; recommend when structured log search is needed
Sentry.logger.* - ⚡ Profiling — JS Self-Profiling API (⚠️ experimental; requires cross-origin isolation headers)
Recommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| Tracing | Always for React SPAs — page load + navigation spans are high-value |
| Session Replay | User-facing app, login flows, or checkout pages |
| Logging | App needs structured log search or log-to-trace correlation |
| Profiling | Performance-critical app; server sends |
React-specific extras:
- React 19 detected → set up on
reactErrorHandler()createRoot - React Router detected → configure matching router integration (see Phase 3)
- Redux detected → add to Redux store
createReduxEnhancer() - Vite detected → configure for source maps (essential for readable stack traces)
sentryVitePlugin
Propose: "I recommend setting up Error Monitoring + Tracing + Session Replay. Want me to also add Logging or Profiling?"
Phase 3: Guide
Install
bash
npm install @sentry/react --saveCreate src/instrument.ts
src/instrument.tsSentry must initialize before any other code runs. Put in a dedicated sidecar file:
Sentry.init()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 Tool | Variable Name | Access in code |
|---|---|---|
| Vite | | |
| Create React App | | |
| Custom webpack | | |
Entry Point Setup
Import as the very first import in your entry file:
instrument.tstsx
// 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>
);React Version-Specific Error Handling
React 19+ — use on :
reactErrorHandler()createRoottsx
import { reactErrorHandler } from "@sentry/react";
createRoot(document.getElementById("root")!, {
onUncaughtError: reactErrorHandler(),
onCaughtError: reactErrorHandler(),
onRecoverableError: reactErrorHandler(),
}).render(<App />);React <19 — wrap your app in :
Sentry.ErrorBoundarytsx
import * as Sentry from "@sentry/react";
createRoot(document.getElementById("root")!).render(
<Sentry.ErrorBoundary fallback={<p>Something went wrong</p>} showDialog>
<App />
</Sentry.ErrorBoundary>
);Use for any sub-tree that should catch errors independently (route sections, widgets, etc.).
<Sentry.ErrorBoundary>Router Integration
Configure the matching integration for your router:
| Router | Integration | Notes |
|---|---|---|
| React Router v7 | | |
| React Router v6 | | |
| React Router v5 | | Wrap routes in |
| TanStack Router | | Pass router instance — no hooks required |
| No router / custom | | 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)],
});Redux Integration (when detected)
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.tstypescript
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 (never commit):
.envbash
SENTRY_AUTH_TOKEN=sntrys_...
SENTRY_ORG=my-org-slug
SENTRY_PROJECT=my-project-slugCreate React App (via CRACO):
bash
npm install @craco/craco @sentry/webpack-plugin --save-devjavascript
// 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:
| Feature | Reference | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) |
| Tracing | | SPA navigation / API call tracing |
| Session Replay | | User-facing app |
| Logging | | Structured log search / log-to-trace |
| Profiling | | Performance-critical app |
| React Features | | Redux, component tracking, source maps, integrations catalog |
For each feature: , follow steps exactly, verify it works.
Read ${SKILL_ROOT}/references/<feature>.mdConfiguration Reference
Key Sentry.init()
Options
Sentry.init()| Option | Type | Default | Notes |
|---|---|---|---|
| | — | Required. SDK disabled when empty |
| | | e.g., |
| | — | e.g., |
| | | Includes IP addresses and request headers |
| | — | 0–1; |
| | — | Per-transaction sampling; overrides rate |
| | — | Outgoing URLs that receive distributed tracing headers |
| | — | Fraction of all sessions recorded |
| | — | Fraction of error sessions recorded |
| | | Enable |
| | | Stack traces on |
| | | Breadcrumbs stored per event |
| | | Verbose SDK output to console |
| | — | Proxy URL to bypass ad blockers |
React Compatibility Matrix
| React Version | Error handling approach | SDK minimum |
|---|---|---|
| React 19+ | | |
| React 16–18 | | |
| React 16 | | |
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 in and check the browser console if nothing appears.
debug: trueSentry.init()Phase 4: Cross-Link
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 -3If a backend exists without Sentry configured, suggest the matching skill:
| Backend detected | Suggest skill |
|---|---|
Go ( | |
Python ( | |
Ruby ( | |
Java ( | Use |
| Node.js (Express, Fastify) | Use |
Troubleshooting
| Issue | Solution |
|---|---|
| Events not appearing | Set |
| Source maps not working | Build in production mode ( |
| Minified stack traces | Source maps not uploading — check plugin config and auth token |
| Verify it's the first import in entry file before React/app imports |
| React 19 errors not captured | Confirm |
| React <19 errors not captured | Ensure |
Router transactions named | Add router integration matching your router version |
| Check regex escaping; default is |
| Session replay not recording | Confirm |
| Redux actions not in breadcrumbs | Add |
| Ad blockers dropping events | Set |
| High replay storage costs | Lower |
| Profiling not working | Verify |