Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
getsentry avatar

Sentry React Sdk

  • 2.6k installs
  • 243 repo stars
  • Updated July 27, 2026
  • getsentry/sentry-for-ai

sentry-react-sdk guides full @sentry/react setup with detect, recommend, and configure phases for React observability.

About

Sentry React SDK is an opinionated wizard scanning React projects and guiding complete @sentry/react setup for error monitoring, tracing, session replay, profiling, and logging. Phase one detects React version, existing Sentry packages, router type, Redux usage, build tool, and adjacent backend directories via package.json and config file inspection. Phase two recommends error monitoring always plus tracing and session replay for SPAs, with optional logging and experimental profiling when cross-origin isolation allows. Phase three installs @sentry/react, creates instrument.ts initialized before other imports, configures browserTracingIntegration and replayIntegration, and sets DSN env vars per Vite, CRA, or webpack. React 19 uses reactErrorHandler on createRoot while earlier versions wrap Sentry.ErrorBoundary. Router integrations cover React Router v5 through v7 non-framework and TanStack Router browser tracing. Redux apps add createReduxEnhancer and Vite projects use sentryVitePlugin for source maps. Framework mode React Router apps should switch to sentry-react-router-framework-sdk instead.

  • Detect React version, router, Redux, and build tool first.
  • instrument.ts must import before all other entry code.
  • React 19 reactErrorHandler versus ErrorBoundary patterns.
  • browserTracingIntegration and replayIntegration defaults.
  • Router and Redux integrations plus Vite source map plugin.

Sentry React Sdk by the numbers

  • 2,551 all-time installs (skills.sh)
  • +52 installs in the week ending Jul 28, 2026 (Skillselion tracking)
  • Ranked #31 of 610 Debugging skills by installs in the Skillselion catalog
  • Security screen: HIGH risk (skills.sh audit)
  • Data as of Jul 28, 2026 (Skillselion catalog sync)
At a glance

sentry-react-sdk capabilities & compatibility

Capabilities
project detection for react, router, and build t · instrument.ts early initialization pattern · version specific error boundary or handler setup · tracing and replay integration configuration · react router and tanstack tracing integrations · redux enhancer and vite source map plugin guidan
Works with
sentry · vercel
Use cases
debugging · ci cd
Pricing
Freemium
npx skills add https://github.com/getsentry/sentry-for-ai --skill sentry-react-sdk

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs2.6k
repo stars243
Security audit3 / 3 scanners passed
Last updatedJuly 27, 2026
Repositorygetsentry/sentry-for-ai

How do I add Sentry error monitoring, tracing, and replay to a React app with the right router integration?

Add Sentry error monitoring, tracing, session replay, and logging to React apps with router and Redux integrations.

Who is it for?

React developers adding production error monitoring, navigation tracing, or session replay.

Skip if: Skip for React Router Framework mode apps that need sentry-react-router-framework-sdk instead.

When should I use this skill?

User asks to add Sentry to React, install @sentry/react, or configure error boundaries and tracing.

What you get

Initialized Sentry with DSN, integrations, version-appropriate error handling, and optional source maps.

  • sentry sdk configuration
  • automatic error capture setup
  • react error handler integration

By the numbers

  • Requires @sentry/react 8.0.0 or newer
  • captureReactException requires @sentry/react 9.8.0+
  • reactErrorHandler requires @sentry/react 8.6.0+

Files

SKILL.mdMarkdownGitHub ↗
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 @sentry/react, React Sentry SDK, or Sentry error boundaries
  • User wants to monitor React Router v5/v6/v7 non-framework navigation, Redux state, or component performance

If project is React Router Framework mode using @sentry/react-router, use sentry-react-router-framework-sdk instead of this skill.

Note: SDK versions and APIs below reflect current Sentry docs at time of writing (@sentry/react ≥8.0.0).
Always verify against docs.sentry.io/platforms/javascript/guides/react/ before implementing.

---

Phase 1: Detect

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

# Detect React version
cat package.json | grep -E '"react"|"react-dom"'

# Check for existing Sentry
cat package.json | grep '"@sentry/'

# Detect router and framework mode hints
cat package.json | grep -E '"react-router-dom"|"react-router"|"@react-router/"|"@tanstack/react-router"|"@sentry/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 -3

What to determine:

QuestionImpact
React 19+?Use reactErrorHandler() hook pattern
React <19?Use Sentry.ErrorBoundary
@sentry/react already present?Skip install, go straight to feature config
React Router Framework mode indicators (@sentry/react-router, @react-router/*)?Use sentry-react-router-framework-sdk
react-router-dom v5 / v6 / v7?Determines which router integration to use
@tanstack/react-router?Use tanstackRouterBrowserTracingIntegration()
Redux in use?Recommend createReduxEnhancer()
Vite detected?Source maps via sentryVitePlugin
CRA (react-scripts)?Source maps via @sentry/webpack-plugin in CRACO
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 Sentry.logger.*; recommend when structured log search is needed
  • Profiling — JS Self-Profiling API (⚠️ experimental; requires cross-origin isolation headers)

Recommendation logic:

FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline
TracingAlways for React SPAs — page load + navigation spans are high-value
Session ReplayUser-facing app, login flows, or checkout pages
LoggingApp needs structured log search or log-to-trace correlation
ProfilingPerformance-critical app; server sends Document-Policy: js-profiling header

React-specific extras:

  • React 19 detected → set up reactErrorHandler() on createRoot
  • React Router v5/v6/v7 non-framework detected → configure matching router integration (see Phase 3)
  • React Router Framework mode detected → switch to sentry-react-router-framework-sdk
  • Redux detected → add createReduxEnhancer() to Redux store
  • Vite detected → configure sentryVitePlugin for source maps (essential for readable stack traces)

Propose: "I recommend setting up Error Monitoring + Tracing + Session Replay. Want me to also add Logging or Profiling?"

---

Phase 3: Guide

Install

npm install @sentry/react --save

Create src/instrument.ts

Sentry must initialize before any other code runs. Put Sentry.init() in a dedicated sidecar file:

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

  dataCollection: {
    // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
    // https://docs.sentry.io/platforms/javascript/guides/react/configuration/options/#dataCollection
    // userInfo: false,
    // httpBodies: [],
  },

  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 ToolVariable NameAccess in code
ViteVITE_SENTRY_DSNimport.meta.env.VITE_SENTRY_DSN
Create React AppREACT_APP_SENTRY_DSNprocess.env.REACT_APP_SENTRY_DSN
Custom webpackSENTRY_DSNprocess.env.SENTRY_DSN

Entry Point Setup

Import instrument.ts as the very first import in your entry file:

// 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 reactErrorHandler() on createRoot:

import { reactErrorHandler } from "@sentry/react";

createRoot(document.getElementById("root")!, {
  onUncaughtError: reactErrorHandler(),
  onCaughtError: reactErrorHandler(),
  onRecoverableError: reactErrorHandler(),
}).render(<App />);

React <19 — wrap your app in Sentry.ErrorBoundary:

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

createRoot(document.getElementById("root")!).render(
  <Sentry.ErrorBoundary fallback={<p>Something went wrong</p>} showDialog>
    <App />
  </Sentry.ErrorBoundary>
);

Use <Sentry.ErrorBoundary> for any sub-tree that should catch errors independently (route sections, widgets, etc.).

Router Integration

Configure the matching integration for your router (non-framework mode):

RouterIntegrationNotes
React Router v7reactRouterV7BrowserTracingIntegrationuseEffect, useLocation, useNavigationType, createRoutesFromChildren, matchRoutes from react-router
React Router v6reactRouterV6BrowserTracingIntegrationuseEffect, useLocation, useNavigationType, createRoutesFromChildren, matchRoutes from react-router-dom
React Router v5reactRouterV5BrowserTracingIntegrationWrap routes in withSentryRouting(Route)
TanStack RoutertanstackRouterBrowserTracingIntegration(router)Pass router instance — no hooks required
No router / custombrowserTracingIntegration()Names transactions by URL path

React Router v6/v7 setup:

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

import { tanstackRouterBrowserTracingIntegration } from "@sentry/react";

// Pass your TanStack router instance:
Sentry.init({
  integrations: [tanstackRouterBrowserTracingIntegration(router)],
});

Redux Integration (when detected)

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.ts`):

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 .env (never commit):

SENTRY_AUTH_TOKEN=sntrys_...
SENTRY_ORG=my-org-slug
SENTRY_PROJECT=my-project-slug

Create React App (via CRACO):

npm install @craco/craco @sentry/webpack-plugin --save-dev
// 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:

FeatureReferenceLoad when...
Error Monitoring${SKILL_ROOT}/references/error-monitoring.mdAlways (baseline)
Tracing${SKILL_ROOT}/references/tracing.mdSPA navigation / API call tracing
Session Replay${SKILL_ROOT}/references/session-replay.mdUser-facing app
Logging${SKILL_ROOT}/references/logging.mdStructured log search / log-to-trace
Profiling${SKILL_ROOT}/references/profiling.mdPerformance-critical app
React Features${SKILL_ROOT}/references/react-features.mdRedux, component tracking, source maps, integrations catalog

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

---

Configuration Reference

Key Sentry.init() Options

OptionTypeDefaultNotes
dsnstringRequired. SDK disabled when empty
environmentstring"production"e.g., "staging", "development"
releasestringe.g., "my-app@1.0.0" or git SHA — links errors to releases
dataCollectionobjectFine-grained control over data collection (see table below); recommended over `sendDefaultPii`
sendDefaultPiibooleanfalse⚠️ Legacy — use dataCollection instead; includes IP addresses and request headers
tracesSampleRatenumber0–1; 1.0 in dev, 0.1–0.2 in prod
tracesSamplerfunctionPer-transaction sampling; overrides rate
tracePropagationTargets`(string\RegExp)[]`
replaysSessionSampleRatenumberFraction of all sessions recorded
replaysOnErrorSampleRatenumberFraction of error sessions recorded
enableLogsbooleanfalseEnable Sentry.logger.* API
attachStacktracebooleanfalseStack traces on captureMessage() calls
maxBreadcrumbsnumber100Breadcrumbs stored per event
debugbooleanfalseVerbose SDK output to console
tunnelstringProxy URL to bypass ad blockers

dataCollection Options (SDK ≥10.57.0)

Fine-grained control over what data the SDK collects. Replaces the simple sendDefaultPii boolean with per-feature toggles:

FieldTypeDefaultNotes
userInfobooleantrueCollect user IP and headers (equivalent to sendDefaultPii: true)
cookies`boolean \{ allow: string[] } \{ deny: string[] }`
httpHeaders.request`boolean \{ allow: string[] } \{ deny: string[] }`
httpHeaders.response`boolean \{ allow: string[] } \{ deny: string[] }`
queryParams`boolean \{ allow: string[] } \{ deny: string[] }`
httpBodiesHttpBodyCollectionTarget[]["incomingRequest", "outgoingRequest", "incomingResponse", "outgoingResponse"]Collect request/response bodies; options: 'incomingRequest', 'outgoingRequest', 'incomingResponse', 'outgoingResponse'
genAI.inputsbooleantrueRecord AI model inputs (for AI monitoring)
genAI.outputsbooleantrueRecord AI model outputs (for AI monitoring)
stackFrameVariablesbooleantrueCapture local variable values in stack frames
frameContextLinesnumber5Source code context lines around stack frames

Example: Allow only specific cookies and headers:

Sentry.init({
  dataCollection: {
    cookies: { allow: ['session', 'user_id'] },
    httpHeaders: {
      request: { allow: ['authorization', 'x-request-id'] },
      response: { deny: ['set-cookie'] },
    },
  },
});

React Compatibility Matrix

React VersionError handling approachSDK minimum
React 19+reactErrorHandler() on createRoot@sentry/react ≥8.0.0
React 16–18Sentry.ErrorBoundary component@sentry/react ≥7.0.0
React 16componentDidCatch class boundaries@sentry/react ≥6.0.0

---

Verification

Trigger test events to confirm Sentry is receiving data:

// 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 debug: true in Sentry.init() and check the browser console if nothing appears.

---

Phase 4: Cross-Link

After completing React setup, check for a companion backend missing Sentry coverage:

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

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 — see docs.sentry.io/platforms/java/
Node.js (Express, Fastify)Use @sentry/node — see docs.sentry.io/platforms/javascript/guides/express/

---

Troubleshooting

IssueSolution
Events not appearingSet debug: true, check DSN, open browser console for SDK errors
Source maps not workingBuild in production mode (npm run build); verify SENTRY_AUTH_TOKEN is set
Minified stack tracesSource maps not uploading — check plugin config and auth token
instrument.ts not running firstVerify it's the first import in entry file before React/app imports
React 19 errors not capturedConfirm reactErrorHandler() is passed to all three createRoot options
React <19 errors not capturedEnsure <Sentry.ErrorBoundary> wraps the component tree
Router transactions named <unknown>Add router integration matching your router version
tracePropagationTargets not matchingCheck regex escaping; default is localhost and your DSN origin only
Session replay not recordingConfirm replayIntegration() is in init; check replaysSessionSampleRate
Redux actions not in breadcrumbsAdd Sentry.createReduxEnhancer() to store enhancers
Ad blockers dropping eventsSet tunnel: "/sentry-tunnel" and add server-side relay endpoint
High replay storage costsLower replaysSessionSampleRate; keep replaysOnErrorSampleRate: 1.0
Profiling not workingVerify Document-Policy: js-profiling header is set on document responses

Related skills

Forks & variants (1)

Sentry React Sdk has 1 known copy in the catalog totaling 337 installs. They canonicalize to this original listing.

FAQ

React 19 or older error handling?

React 19 uses reactErrorHandler on createRoot; older versions wrap Sentry.ErrorBoundary.

Where put Sentry.init?

In src/instrument.ts imported as the very first line of the entry file.

Vite DSN variable name?

Use VITE_SENTRY_DSN accessed via import.meta.env.VITE_SENTRY_DSN.

Is Sentry React Sdk safe to install?

skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

Debuggingmonitoring

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.