React
Learn how to manually set up Sentry in your React app and capture your first errors.
You need:
Choose the features you want to configure, and this guide will show you how:
Run the command for your preferred package manager to add the Sentry SDK to your application:
npm install @sentry/react --save
Sentry supports multiple versions of React Router. To learn how to configure them, read the React Router Integration docs.
To import and initialize Sentry, create a file in your project's root directory, for example, instrument.js
, and add the following code:
instrument.js
import { useEffect } from "react";
import * as Sentry from "@sentry/react";
import {
createRoutesFromChildren,
matchRoutes,
useLocation,
useNavigationType,
} from "react-router-dom";
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
// See docs for support of different versions of variation of react router
// https://docs.sentry.io/platforms/javascript/guides/react/configuration/integrations/react-router/
Sentry.reactRouterV6BrowserTracingIntegration({
useEffect,
useLocation,
useNavigationType,
createRoutesFromChildren,
matchRoutes,
}),
Sentry.replayIntegration(),
],
// Set tracesSampleRate to 1.0 to capture 100%
// of transactions for tracing.
// Learn more at
// https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate
tracesSampleRate: 1.0,
// Set `tracePropagationTargets` to control for which URLs trace propagation should be enabled
tracePropagationTargets: [/^\//, /^https:\/\/yourserver\.io\/api/],
// Capture Replay for 10% of all sessions,
// plus for 100% of sessions with an error
// Learn more at
// https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
Initialize Sentry as early as possible in your application. We recommend putting the import of your initialization code as the first import in your app's entry point:
// Sentry initialization should be imported first!
import "./instrument";
import App from "./App";
import { createRoot } from "react-dom/client";
const container = document.getElementById(“app”);
const root = createRoot(container);
root.render(<App />);
To make sure Sentry captures all your app's errors, configure error handling based on your React version.
The createRoot
and hydrateRoot
methods provide error hooks to capture errors automatically. These hooks apply to all React components mounted to the root container. Integrate Sentry with these hooks and customize error handling:
import { createRoot } from "react-dom/client";
const container = document.getElementById(“app”);
const root = createRoot(container, {
// Callback called when an error is thrown and not caught by an ErrorBoundary.
onUncaughtError: Sentry.reactErrorHandler((error, errorInfo) => {
console.warn('Uncaught error', error, errorInfo.componentStack);
}),
// Callback called when React catches an error in an ErrorBoundary.
onCaughtError: Sentry.reactErrorHandler(),
// Callback called when React automatically recovers from errors.
onRecoverableError: Sentry.reactErrorHandler(),
});
root.render();
Use the ErrorBoundary
component to automatically send errors from specific component trees to Sentry and provide a fallback UI:
import React from "react";
import * as Sentry from "@sentry/react";
<Sentry.ErrorBoundary fallback={<p>An error has occurred</p>}>
<Example />
</Sentry.ErrorBoundary>;
To capture errors manually with your own error boundary, use the captureReactException
function as described here.
The React Router integration is designed to work with our tracing package. Learn more about set up for our React Router Integration.
To capture Redux state data, use Sentry.createReduxEnhancer
when initializing your Redux store.
import { configureStore, createStore, compose } from "redux";
import * as Sentry from "@sentry/react";
// ...
const sentryReduxEnhancer = Sentry.createReduxEnhancer({
// Optionally pass options listed below
});
// If you are using the `configureStore` API, pass the enhancer as follows:
const store = configureStore({
reducer,
enhancers: (getDefaultEnhancers) => {
return getDefaultEnhancers().concat(sentryReduxEnhancer);
},
});
// If you are using the deprecated `createStore` API, pass the enhancer as follows:
const store = createStore(reducer, sentryReduxEnhancer);
The stack traces in your Sentry errors probably won't look like your actual code. To fix this, upload your source maps to Sentry. The easiest way to do this is by using the Sentry Wizard:
npx @sentry/wizard@latest -i sourcemaps
Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.
Add the following test button to one of your pages, which will trigger an error that Sentry will capture when you click it:
<button
type="button"
onClick={() => {
throw new Error("Sentry Test Error");
}}
>
Break the world
</button>;
Open the page in a browser (for most React applications, this will be at localhost) and click the button to trigger a frontend error.
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 and should already be sending data to your Sentry project.
Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are:
- Extend Sentry to your backend using one of our SDKs
- Continue to customize your configuration
- Make use of React-specific features
- Learn how to manually capture errors
- Avoid ad-blockers with tunneling
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").