React

Learn how to set up and configure Sentry in your React application.

AI Rules for Code Editors

Sentry provides a set of rules you can use to help your LLM use Sentry correctly. Copy this file and add it to your projects rules configuration. When created as a rules file this should be placed alongside other editor specific rule files. For example, if you are using Cursor, place this file in the .cursorrules directory.

rules.md
Copied
These examples should be used as guidance when configuring Sentry functionality within a project.

# Error / Exception Tracking

- Use `Sentry.captureException(error)` to capture an exception and log the error in Sentry.
- Use this in try catch blocks or areas where exceptions are expected

# Tracing Examples

- Spans should be created for meaningful actions within an applications like button clicks, API calls, and function calls
- Ensure you are creating custom spans with meaningful names and operations
- Use the `Sentry.startSpan` function to create a span
- Child spans can exist within a parent span

## Custom Span instrumentation in component actions

```javascript
function TestComponent() {
  const handleTestButtonClick = () => {
    // Create a transaction/span to measure performance
    Sentry.startSpan(
      {
        op: "ui.click",
        name: "Test Button Click",
      },
      (span) => {
        const value = "some config";
        const metric = "some metric";

        // Metrics can be added to the span
        span.setAttribute("config", value);
        span.setAttribute("metric", metric);

        doSomething();
      },
    );
  };

  return (
    <button type="button" onClick={handleTestButtonClick}>
      Test Sentry
    </button>
  );
}
```

## Custom span instrumentation in API calls

```javascript
async function fetchUserData(userId) {
  return Sentry.startSpan(
    {
      op: "http.client",
      name: `GET /api/users/${userId}`,
    },
    async () => {
      const response = await fetch(`/api/users/${userId}`);
      const data = await response.json();
      return data;
    },
  );
}
```

# Logs

- Where logs are used, ensure Sentry is imported using `import * as Sentry from "@sentry/react"`
- Enable logging in Sentry using `Sentry.init({ enableLogs: true })`
- Reference the logger using `const { logger } = Sentry`
- Sentry offers a consoleLoggingIntegration that can be used to log specific console error types automatically without instrumenting the individual logger calls

## Configuration

### Baseline

```javascript
import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

  enableLogs: true,
});
```

### Logger Integration

```javascript
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    // send console.log, console.error, and console.warn calls as logs to Sentry
    Sentry.consoleLoggingIntegration({ levels: ["log", "error", "warn"] }),
  ],
});
```

## Logger Examples

`logger.fmt` is a template literal function that should be used to bring variables into the structured logs.

```javascript
logger.trace("Starting database connection", { database: "users" });
logger.debug(logger.fmt`Cache miss for user: ${userId}`);
logger.info("Updated profile", { profileId: 345 });
logger.warn("Rate limit reached for endpoint", {
  endpoint: "/api/results/",
  isEnterprise: false,
});
logger.error("Failed to process payment", {
  orderId: "order_123",
  amount: 99.99,
});
logger.fatal("Database connection pool exhausted", {
  database: "users",
  activeConnections: 100,
});
```

You need:

Select which Sentry features you'd like to configure to get the corresponding setup instructions below.

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.

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

Copied
npm install @sentry/react --save

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

Add the following to your application's entry point (typically index.js, main.js, or App.js) or to the file before you use any other Sentry method:

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

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

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

  integrations: [
    //  performance
    Sentry.browserTracingIntegration(),
    //  performance
    //  session-replay
    Sentry.replayIntegration(),
    //  session-replay
    //  user-feedback
    Sentry.feedbackIntegration({
      // Additional SDK configuration goes in here, for example:
      colorScheme: "system",
    }),
    //  user-feedback
    //  logs
    Sentry.consoleLoggingIntegration({ levels: ["log", "warn", "error"] }),
    //  logs
  ],

  //  logs
  // For help logging, see: https://docs.sentry.io/platforms/javascript/guides/react/logging/
  enableLogs: true,
  //  logs

  //  performance
  // Set sample rate for performance monitoring
  // We recommend adjusting this value in production
  tracesSampleRate: 1.0,
  //  performance

  //  session-replay
  // For session replay
  // See: https://docs.sentry.io/platforms/javascript/session-replay/
  replaysSessionSampleRate: 0.1, // Sample 10% of sessions
  replaysOnErrorSampleRate: 1.0, // Sample 100% of sessions with an error
  //  session-replay

  //  logs
  // For help logging, see: https://docs.sentry.io/platforms/javascript/guides/react/logging/
  extraErrorDataIntegration: false,
  //  logs
});

Import the instrument.js file in your application's entry point before all other imports to initialize the SDK:

index.jsx
Copied
import "./instrument.js";
import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import App from "./App"; const container = document.getElementById("root"); 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.

Starting with React 19, use the onCaughtError and onUncaughtError root options to capture React errors:

index.jsx
Copied
import "./instrument.js";
import * as Sentry from "@sentry/react";
import { createRoot } from "react-dom/client";
import App from "./App";

const container = document.getElementById("root");
const root = createRoot(container, {
  // Callback for errors caught by React error boundaries
onCaughtError: Sentry.reactErrorHandler((error, errorInfo) => { console.error("Caught error:", error, errorInfo.componentStack); }), // Callback for errors not caught by React error boundaries onUncaughtError: Sentry.reactErrorHandler(), }); root.render(<App />);

Use the Sentry Error Boundary to wrap your application:

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

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

Structured logging lets users send text-based log information from their applications to Sentry. Once in Sentry, these logs can be viewed alongside relevant errors, searched by text-string, or searched using their individual attributes.

Use Sentry's logger to capture structured logs with meaningful attributes that help you debug issues and understand user behavior.

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

const { logger } = Sentry;

// Send structured logs with attributes
logger.info("User completed checkout", {
  userId: 123,
  orderId: "order_456",
  amount: 99.99,
});

logger.error("Payment processing failed", {
  errorCode: "CARD_DECLINED",
  userId: 123,
  attemptCount: 3,
});

// Using template literals for dynamic data
logger.warn(logger.fmt`Rate limit exceeded for user: ${userId}`);

Replays allow you to see video-like reproductions of user sessions.

By default, Session Replay masks sensitive data for privacy and to protect PII data. You can modify the replay configurations in your client-side Sentry initialization to show (unmask) specific content that's safe to display.

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

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    Sentry.replayIntegration({
      // This will show the content of the div with the class "reveal-content" and the span with the data-safe-to-show attribute
      unmask: [".reveal-content", "[data-safe-to-show]"],
      // This will show all text content in replays. Use with caution.
      maskAllText: false,
      // This will show all media content in replays. Use with caution.
      blockAllMedia: false,
    }),
  ],
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  // ... your existing config
});

Tracing allows you to monitor interactions between multiple services or applications. Create custom spans to measure specific operations and add meaningful attributes. This helps you understand performance bottlenecks and debug issues with detailed context.

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

// Create custom spans to measure specific operations
async function processUserData(userId) {
  return await Sentry.startSpan(
    {
      name: "Process User Data",
      op: "function",
      attributes: {
        userId: userId,
        operation: "data_processing",
        version: "2.1",
      },
    },
    async () => {
      // Your business logic here
      const userData = await fetchUserData(userId);

      // Nested span for specific operations
      return await Sentry.startSpan(
        {
          name: "Transform Data",
          op: "transform",
          attributes: {
            recordCount: userData.length,
            transformType: "normalize",
          },
        },
        () => {
          return transformUserData(userData);
        },
      );
    },
  );
}

// Add attributes to existing spans
const span = Sentry.getActiveSpan();
if (span) {
  span.setAttributes({
    cacheHit: true,
    region: "us-west-2",
    performanceScore: 0.95,
  });
}

You can prevent ad blockers from blocking Sentry events using tunneling. Use the tunnel option to add an API endpoint in your application that forwards Sentry events to Sentry servers.

To enable tunneling, update Sentry.init with the following option:

Copied
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",,
tunnel: "/tunnel",
});

This will send all events to the tunnel endpoint. However, the events need to be parsed and redirected to Sentry, so you'll need to do additional configuration on the server. You can find a detailed explanation on how to do this on our Troubleshooting page.

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 more details, see this interactive walkthrough.
  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.
  4. Open the Logs page and filter by service, environment, or search keywords to view log entries from your application. For an interactive UI walkthrough, click here.

At this point, you should have integrated Sentry into your React application and should already be sending error and performance data to your Sentry project.

Now's a good time to customize your setup and look into more advanced topics:

Set Up React Router (Optional)

If you're using react-router in your application, you need to set up the Sentry integration for your specific React Router version to trace navigation events.

Select your React Router version to start instrumenting your routing:

Capture Redux State Data (Optional)

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