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:

Want to learn more about these features?
  • Issues (always enabled): Sentry's core error monitoring product that automatically reports errors, uncaught exceptions, and unhandled rejections. If you have something that looks like an exception, Sentry can capture it.
  • Tracing: Track software performance while seeing the impact of errors across multiple systems. For example, distributed tracing allows you to follow a request from the frontend to the backend and back.
  • Session Replay: Get to the root cause of an issue faster by viewing a video-like reproduction of what was happening in the user's browser before, during, and after the problem.

Run the command for your preferred package manager to add the Sentry SDK to your application:

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

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

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

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

<Sentry.ErrorBoundary fallback={<p>An error has occurred</p>}>
  <Example />
</Sentry.ErrorBoundary>;

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.

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

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

Copied
<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.

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).

Need help locating the captured errors in your Sentry project?
  1. Open the Issues page and select an error from the issues list to view the full details and context of this error. For an interactive UI walkthrough, click here.
  2. Open the Traces page and select a trace to reveal more information about each span, its duration, and any errors. For an interactive UI walkthrough, click here.
  3. Open the Replays page and select an entry from the list to get a detailed view where you can replay the interaction and get more information to help you troubleshoot.

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:

Are you having problems setting up the SDK?
Was this helpful?
Help improve this content
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").