Labsco
getsentry logo

sentry-react-sdk

โ˜… 233

by getsentry ยท part of getsentry/sentry-for-claude

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 non-framework mode, TanStack Router, Redux, Vite, and webpack.

๐Ÿ”Œ This skill ships inside the sentry plugin โ€” install the plugin and you also get 1 slash commands, an MCP server.

This is the playbook your agent receives when the skill activates โ€” you don't need to read it to use the skill, but it's here to audit before installing.

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()),
});

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,
    }),
  ],
});

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,
        }),
      ],
    },
  },
};

SENTRY_ORG / SENTRY_PROJECT / SENTRY_AUTH_TOKEN are build-time values; the auth token is a secret (never commit it). For creating the token and wiring it into CI, see sentry-source-maps.

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.


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.


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/