Sentry for React
Learn how to set up Sentry in your React application and capture your first events.
Use curl to download, read and follow https://skills.sentry.dev/instrument to set up the Sentry React SDK.You need:
Run the command for your preferred package manager to add the Sentry SDK to your application:
npm install @sentry/react --save
npm install @sentry/react --save
yarn add @sentry/react
pnpm add @sentry/react
Error Monitoring starts working as soon as you call Sentry.init(). Logs and Application Metrics need no extra configuration, and you'll learn how to send them in steps #3 and #4. This guide also enables Tracing, Session Replay, and User Feedback.
Create a file in your project's root directory (for example, instrument.js) and add your Sentry configuration. Import this file before any other imports in your application entry point.
The snippet also turns on:
- Tracing: via
browserTracingIntegration()andtracesSampleRate;tracePropagationTargetscontrols which API requests receive trace headers - Session Replay: via
replayIntegration(), sampled withreplaysSessionSampleRateandreplaysOnErrorSampleRate - User Feedback: via
feedbackIntegration()
Don't need a feature? Remove its integration and options from the snippet.
instrument.jsimport * as Sentry from "@sentry/react";
Sentry.init({
dsn: "___PUBLIC_DSN___",
integrations: [
// enables automatic instrumentation
Sentry.browserTracingIntegration(),
// enables Session Replay
Sentry.replayIntegration(),
// enables User Feedback
Sentry.feedbackIntegration({
// Additional integration configuration goes in here
colorScheme: "system",
}),
],
// Enables Tracing.
// Set to 1.0 to capture 100% of spans for tracing.
// We recommend reducing this value in production.
tracesSampleRate: 1.0,
// Set trace propagation targets for your API requests
tracePropagationTargets: [/^\//, /^https:\/\/yourserver\.io\/api/],
// Capture replays for 10% of all sessions,
// plus for 100% of sessions with an error
// Requires Sentry.replayIntegration()
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
import * as Sentry from "@sentry/react";
Sentry.init({
dsn: "___PUBLIC_DSN___",
integrations: [
// enables automatic instrumentation
Sentry.browserTracingIntegration(),
// enables Session Replay
Sentry.replayIntegration(),
// enables User Feedback
Sentry.feedbackIntegration({
// Additional integration configuration goes in here
colorScheme: "system",
}),
],
// Enables Tracing.
// Set to 1.0 to capture 100% of spans for tracing.
// We recommend reducing this value in production.
tracesSampleRate: 1.0,
// Set trace propagation targets for your API requests
tracePropagationTargets: [/^\//, /^https:\/\/yourserver\.io\/api/],
// Capture replays for 10% of all sessions,
// plus for 100% of sessions with an error
// Requires Sentry.replayIntegration()
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
Import your Sentry configuration as the first import in your application entry point, then render your app.
main.jsximport "./instrument";
import App from "./App";
import { createRoot } from "react-dom/client";
const container = document.getElementById("app");
const root = createRoot(container);
root.render(<App />);
import "./instrument";
import App from "./App";
import { createRoot } from "react-dom/client";
const container = document.getElementById("app");
const root = createRoot(container);
root.render(<App />);
React 19 introduced error hooks that integrate directly with Sentry. Configure createRoot or hydrateRoot with error handlers using reactErrorHandler for comprehensive error capture.
main.jsximport "./instrument";
import App from "./App";
import { createRoot } from "react-dom/client";
import * as Sentry from "@sentry/react";
const container = document.getElementById("app");
const root = createRoot(container, {
// Called when an error is thrown and not caught by an ErrorBoundary.
onUncaughtError: Sentry.reactErrorHandler((error, errorInfo) => {
console.warn("Uncaught error", error, errorInfo.componentStack);
}),
// Called when React catches an error in an ErrorBoundary.
onCaughtError: Sentry.reactErrorHandler(),
// Called when React automatically recovers from errors.
onRecoverableError: Sentry.reactErrorHandler(),
});
root.render(<App />);
import "./instrument";
import App from "./App";
import { createRoot } from "react-dom/client";
import * as Sentry from "@sentry/react";
const container = document.getElementById("app");
const root = createRoot(container, {
// Called when an error is thrown and not caught by an ErrorBoundary.
onUncaughtError: Sentry.reactErrorHandler((error, errorInfo) => {
console.warn("Uncaught error", error, errorInfo.componentStack);
}),
// Called when React catches an error in an ErrorBoundary.
onCaughtError: Sentry.reactErrorHandler(),
// Called when React automatically recovers from errors.
onRecoverableError: Sentry.reactErrorHandler(),
});
root.render(<App />);
Source maps are essential for debugging production errors. Without them, stack traces point to minified code.
Run the Sentry wizard to configure source map uploads for your bundler:
- Vite — Recommended for new projects
- Webpack — Common in existing projects
- Rollup or esbuild — For custom setups
npx @sentry/wizard@latest -i sourcemaps
npx @sentry/wizard@latest -i sourcemaps
If you're using client-side routing, configure Sentry to capture navigation events for better performance insights.
When using React Router, replace browserTracingIntegration() with the integration for your router version. For example:
instrument.jsimport React from "react";
import * as Sentry from "@sentry/react";
import {
useLocation,
useNavigationType,
createRoutesFromChildren,
matchRoutes,
} from "react-router";
Sentry.init({
dsn: "___PUBLIC_DSN___",
integrations: [
// enables automatic instrumentation for React Router v7
Sentry.reactRouterV7BrowserTracingIntegration({
useEffect: React.useEffect,
useLocation,
useNavigationType,
createRoutesFromChildren,
matchRoutes,
}),
// enables Session Replay
Sentry.replayIntegration(),
// enables User Feedback
Sentry.feedbackIntegration({
colorScheme: "system",
}),
],
// Enables Tracing.
// Set to 1.0 to capture 100% of spans for tracing.
// We recommend reducing this value in production.
tracesSampleRate: 1.0,
tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/],
// Capture replays for 10% of all sessions,
// plus for 100% of sessions with an error
// Requires Sentry.replayIntegration()
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
import React from "react";
import * as Sentry from "@sentry/react";
import {
useLocation,
useNavigationType,
createRoutesFromChildren,
matchRoutes,
} from "react-router";
Sentry.init({
dsn: "___PUBLIC_DSN___",
integrations: [
// enables automatic instrumentation for React Router v7
Sentry.reactRouterV7BrowserTracingIntegration({
useEffect: React.useEffect,
useLocation,
useNavigationType,
createRoutesFromChildren,
matchRoutes,
}),
// enables Session Replay
Sentry.replayIntegration(),
// enables User Feedback
Sentry.feedbackIntegration({
colorScheme: "system",
}),
],
// Enables Tracing.
// Set to 1.0 to capture 100% of spans for tracing.
// We recommend reducing this value in production.
tracesSampleRate: 1.0,
tracePropagationTargets: [/^\\//, /^https:\\/\\/yourserver\\.io\\/api/],
// Capture replays for 10% of all sessions,
// plus for 100% of sessions with an error
// Requires Sentry.replayIntegration()
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
Capture Redux state and actions with your errors using Sentry.createReduxEnhancer. Learn more about Redux integration options.
store.jsimport { createStore, compose } from "redux";
import * as Sentry from "@sentry/react";
const sentryEnhancer = Sentry.createReduxEnhancer();
const store = createStore(rootReducer, compose(sentryEnhancer));
import { createStore, compose } from "redux";
import * as Sentry from "@sentry/react";
const sentryEnhancer = Sentry.createReduxEnhancer();
const store = createStore(rootReducer, compose(sentryEnhancer));
By default, the SDK sends user identity data (IP address, ID, and similar) and other data like HTTP bodies and URL query parameters. This will give you rich debugging context.
The SDK always filters sensitive values whose keys match a built-in denylist, such as auth or password, and sends [Filtered] instead.
To send less data, turn off the categories you don't need in the dataCollection option. For the full list of categories and their defaults, see the dataCollection options.
Sentry.init({
dsn: "___PUBLIC_DSN___",
dataCollection: {
userInfo: false,
// other categories
},
});
Sentry.init({
dsn: "___PUBLIC_DSN___",
dataCollection: {
userInfo: false,
// other categories
},
});
Use Sentry.logger to send logs at different levels, such as info, warn, or error. You can pass any attributes you want and search or filter by them later. See Set Up Logs for all available logging methods and the syntax for formatting messages.
Sentry.logger.info("User example action completed");
Sentry.logger.warn("Slow operation detected", {
operation: "data_fetch",
duration: 3500,
});
Sentry.logger.error("Validation failed", {
form_field: "email",
reason: "Invalid email",
});
Sentry.logger.info("User example action completed");
Sentry.logger.warn("Slow operation detected", {
operation: "data_fetch",
duration: 3500,
});
Sentry.logger.error("Validation failed", {
form_field: "email",
reason: "Invalid email",
});
If you're already logging with console or Consola, you can capture those logs with our console integrations.
Use Sentry.metrics to send counters, gauges, and distributions from your app to Sentry. You can pass any attributes you want and search or filter by them later. See Set Up Metrics for all available metric types and configuration options.
Sentry.metrics.count("checkout.failed", 1);
Sentry.metrics.gauge("time_since_refresh", 4, { unit: "hour" });
Sentry.metrics.distribution("api_latency", 187, {
unit: "millisecond",
attributes: { endpoint: "/api/orders" },
});
Sentry.metrics.count("checkout.failed", 1);
Sentry.metrics.gauge("time_since_refresh", 4, { unit: "hour" });
Sentry.metrics.distribution("api_latency", 187, {
unit: "millisecond",
attributes: { endpoint: "/api/orders" },
});
Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.
Add a test button to one of your components. Clicking it will trigger an error for Sentry to capture.
App.jsx<button
type="button"
onClick={() => {
throw new Error("Sentry Test Error");
}}
>
Test Sentry Error
</button>;
<button
type="button"
onClick={() => {
throw new Error("Sentry Test Error");
}}
>
Test Sentry Error
</button>;
Important
Errors triggered from within your browser's developer tools (like the browser console) are sandboxed, so they will not trigger Sentry's error monitoring.
Now, head over to your project on Sentry.io to view the collected data (it takes a couple of moments for the data to appear).
At this point, you should have integrated Sentry into your React application. Here's what to explore next:
- Explore practical guides on what to monitor, log, track, and investigate after setup
- Set up tunneling to avoid ad blockers from blocking Sentry events
- Explore React-specific features
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").