React

Learn how to set up Sentry in your React application, capture your first errors and traces, and view them in Sentry.

Sentry Agent Skills

Install Sentry's agent skills to teach your AI coding assistant how to set up and use Sentry in your React application.

Copied
npx @sentry/dotagents add getsentry/sentry-agent-skills --all

See the full list of available skills and installation docs for more details.

You need:

Install the Sentry SDK using your preferred package manager:

Copied
npm install @sentry/react --save

Choose the features you want to configure:

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.
  • Logs: Centralize and analyze your application logs to correlate them with errors and performance issues. Search, filter, and visualize log data to understand what's happening in your applications.

Create a file in your project's root directory (e.g., instrument.js) and add your Sentry configuration.

This file must be imported before any other imports in your application entry point.

instrument.js
Copied
import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: "___PUBLIC_DSN___",

  // Adds request headers and IP for users, for more info visit:
  // https://docs.sentry.io/platforms/javascript/guides/react/configuration/options/#sendDefaultPii
  sendDefaultPii: true,

    // ___PRODUCT_OPTION_START___ performance
    // If you're using react router, use the integration for your react router version instead.
    // Learn more at
    // https://docs.sentry.io/platforms/javascript/guides/react/configuration/integrations/react-router/
    Sentry.browserTracingIntegration(),
    // ___PRODUCT_OPTION_END___ performance
    // ___PRODUCT_OPTION_START___ session-replay
    Sentry.replayIntegration(),
    // ___PRODUCT_OPTION_END___ session-replay
    // ___PRODUCT_OPTION_START___ user-feedback
    Sentry.feedbackIntegration({
      // Additional SDK configuration goes in here, for example:
      colorScheme: "system",
    }),
    // ___PRODUCT_OPTION_END___ user-feedback
  // ___PRODUCT_OPTION_START___ logs

  // Enable logs to be sent to Sentry
  enableLogs: true,
  // ___PRODUCT_OPTION_END___ logs
  // ___PRODUCT_OPTION_START___ performance

  // 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/],
  // ___PRODUCT_OPTION_END___ performance
  // ___PRODUCT_OPTION_START___ session-replay

  // 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,
  // ___PRODUCT_OPTION_END___ session-replay
});

Import your Sentry configuration as the first import in your application entry point, then render your app.

main.jsx
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 />);

React 19 introduced error hooks that integrate directly with Sentry. Configure createRoot or hydrateRoot with error handlers using reactErrorHandler for comprehensive error capture.

main.jsx
Copied
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, {
  // 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(<App />);
Using React 18 or below?

Use the ErrorBoundary component to capture rendering errors and display a fallback UI.

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

function App() {
  return (
    <Sentry.ErrorBoundary fallback={<p>An error has occurred</p>}>
      <YourAppContent />
    </Sentry.ErrorBoundary>
  );
}

Learn more about ErrorBoundary options.

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:

Copied
npx @sentry/wizard@latest -i sourcemaps

If you're using client-side routing, configure Sentry to capture navigation events for better performance insights.

Select your router:

instrument.js
Copied
import React from "react";
import * as Sentry from "@sentry/react";
import {
  useLocation,
  useNavigationType,
  createRoutesFromChildren,
  matchRoutes,
} from "react-router";

Sentry.init({
  dsn: "___PUBLIC_DSN___",
  integrations: [
    Sentry.reactRouterV7BrowserTracingIntegration({
      useEffect: React.useEffect,
      useLocation,
      useNavigationType,
      createRoutesFromChildren,
      matchRoutes,
    }),
  ],
});

Capture Redux state and actions with your errors using Sentry.createReduxEnhancer.

Learn more about Redux integration options.

store.js
Copied
import { createStore, compose } from "redux";
import * as Sentry from "@sentry/react";

const sentryEnhancer = Sentry.createReduxEnhancer();

const store = createStore(rootReducer, compose(sentryEnhancer));

Some ad blockers prevent Sentry events from being sent. Use the tunnel option to route events through your server.

Learn more about setting up tunneling.

instrument.js
Copied
Sentry.init({
  dsn: "___PUBLIC_DSN___",
  tunnel: "/tunnel",
});

Add a test button to trigger an error, then check Sentry to confirm it's working.

ErrorsOpen Issues

You should see "Sentry Test Error" with a stack trace pointing to your source code (if source maps are configured).

TracingOpen Traces

You should see page load traces and the test span. Learn more about custom instrumentation.

Session ReplayOpen Replays

Watch a video-like recording of your session, including the moment the error occurred. Learn more about Session Replay configuration.

LogsOpen Logs NEW

See structured log entries from your application. Learn more about Logs configuration.

App.jsx
Copied
<button
  type="button"
  onClick={() => {
    throw new Error("Sentry Test Error");
  }}
>
  Break the world
</button>;

To test tracing, wrap the error in a span:

Copied
<button
  type="button"
  onClick={() => {
    Sentry.startSpan({ op: "test", name: "Example Frontend Span" }, () => {
      setTimeout(() => {
        throw new Error("Sentry Test Error");
      }, 99);
    });
  }}
>
  Break the world
</button>;

Send logs from anywhere in your app:

Copied
Sentry.logger.info("User action", { userId: "123" });
Sentry.logger.warn("Slow response", { duration: 5000 });
Sentry.logger.error("Operation failed", { reason: "timeout" });
Not seeing events in Sentry?

1. Enable debug mode to see SDK activity in the console:

instrument.js
Copied
Sentry.init({
  dsn: "___PUBLIC_DSN___",
  debug: true,
});

2. Check your DSN — Ensure it's correctly copied from your Sentry project settings.

3. Disable ad blockers — Some ad blockers prevent Sentry from sending events. See tunneling for a workaround.

4. Check your quota — View your usage stats to ensure you haven't exceeded your plan limits.

For more help, see the Troubleshooting page.

You've successfully 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
  • Session Replay — Watch video-like reproductions of user sessions to debug errors in context
  • Distributed Tracing — Trace requests from your React frontend to backend services
  • Connect GitHub + Seer — Enable AI-powered root cause analysis by connecting your repository
  • Logs — Send structured logs correlated with errors and traces
  • Metrics BETA— Track custom counters, gauges, and distributions to monitor application health
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").