---
title: "Manual Setup"
description: "Learn how to manually set up Sentry in your React Router app (v7.15+) and capture your first events."
url: https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup/
---

# Manual Setup for React Router Framework

Looking for automatic setup with `sentry init` or the React Router Framework Mode wizard? Follow the [React Router quickstart](https://docs.sentry.io/platforms/javascript/guides/react-router.md) instead. Continue with this guide to set up Sentry manually.

## [Prerequisites](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#prerequisites)

You need:

* A Sentry [account](https://sentry.io/signup/) and [project](https://docs.sentry.io/product/projects.md)
* Your application up and running
* React Router version `7.15.0` or above (framework mode)

## [Install](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#install)

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

```bash
npm install @sentry/react-router @sentry/profiling-node
```

*Other available variations of the above snippet: yarn, pnpm*

## [Configure](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#configure)

**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](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#send-logs) and [#4](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#send-application-metrics-). This guide also enables **Tracing**, **Profiling**, **Session Replay**, and **User Feedback**.

Want to learn more about these features?

* [**Issues**](https://docs.sentry.io/product/issues.md) (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**](https://docs.sentry.io/product/tracing.md): 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.
* [**Profiling**](https://docs.sentry.io/product/profiling.md): Gain deeper insight than traditional tracing without custom instrumentation, letting you discover slow-to-execute or resource-intensive functions in your app.
* [**Session Replay**](https://docs.sentry.io/product/session-replay/web.md): 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**](https://docs.sentry.io/product/logs.md): 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.
* [**Application Metrics**](https://docs.sentry.io/product/metrics.md) (always enabled): Track and analyze custom application metrics, such as response times and database query durations, to understand trends and patterns in your application's performance and behavior over time.
* [**User Feedback**](https://docs.sentry.io/product/user-feedback.md): Collect feedback directly from users when they encounter errors, allowing them to describe what happened and provide context that helps you understand and resolve issues faster.

### [Expose Entry Point Files](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#expose-entry-point-files)

Before configuring Sentry, you need to make React Router's entry files (`entry.client.tsx` and `entry.server.tsx`) visible in your project. Run this command to expose them:

```bash
npx react-router reveal
```

### [Configure Client-Side Sentry](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#configure-client-side-sentry)

Initialize Sentry in your `entry.client.tsx` file.

The snippet also turns on:

* Tracing: via [`tracesSampleRate`](https://docs.sentry.io/platforms/javascript/guides/react-router/configuration/options.md#tracesSampleRate) and `reactRouterTracingIntegration()`
* Session Replay: via `replayIntegration()`, sampled with [`replaysSessionSampleRate`](https://docs.sentry.io/platforms/javascript/guides/react-router/configuration/options.md#replaysSessionSampleRate) and [`replaysOnErrorSampleRate`](https://docs.sentry.io/platforms/javascript/guides/react-router/configuration/options.md#replaysOnErrorSampleRate)
* User Feedback: via [`feedbackIntegration()`](https://docs.sentry.io/platforms/javascript/guides/react-router/user-feedback/configuration.md)

Don't need a feature? Remove its integration and options from the snippet.

The `sentryOnError` handler integrates with React Router's [`onError` hook](https://reactrouter.com/how-to/error-reporting) to automatically capture and report client-side errors to Sentry.

```tsx
import * as Sentry from "@sentry/react-router";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";

Sentry.init({
  dsn: "https://<key>@o<orgId>.ingest.sentry.io/<projectId>",

  integrations: [
    // Registers and configures the Tracing integration,
    // which automatically instruments your application to monitor its
    // performance, including custom React Router routing instrumentation
    Sentry.reactRouterTracingIntegration(),
    // Registers the Replay integration,
    // which automatically captures Session Replays
    Sentry.replayIntegration(),
    // Registers the User Feedback integration
    Sentry.feedbackIntegration({
      // Additional SDK configuration goes in here, for example:
      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 `tracePropagationTargets` to declare which URL(s) should have trace propagation enabled
  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,
});

startTransition(() => {
  hydrateRoot(
    document,
    <StrictMode>
      <HydratedRouter onError={Sentry.sentryOnError} />
    </StrictMode>,
  );
});
```

### [Configure Server-Side Sentry](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#configure-server-side-sentry)

Limited Node support for OpenTelemetry auto-instrumentation

Sentry's OpenTelemetry-based auto-instrumentation (loaded through `instrument.server.mjs`) is currently only supported on:

* **Node 20:** Version <20.19
* **Node 22:** Version <22.12

This restriction **doesn't** affect tracing for loaders, actions, middleware, and request handlers. Those are instrumented through React Router's [instrumentation API](https://reactrouter.com/how-to/instrumentation) (the `instrumentations` export shown below), which works on all Node versions.

On unsupported Node versions, you'll only lose auto-instrumentation for lower-level operations such as outgoing HTTP requests and database queries.

First, create a file called `instrument.server.mjs` in the root of your project to initialize Sentry.

The snippet also turns on:

* Tracing: via [`tracesSampleRate`](https://docs.sentry.io/platforms/javascript/guides/react-router/configuration/options.md#tracesSampleRate)
* Profiling: via `nodeProfilingIntegration()` and [`profileSessionSampleRate`](https://docs.sentry.io/platforms/javascript/guides/react-router/configuration/options.md#profileSessionSampleRate)

Don't need a feature? Remove its integration and options from the snippet.

```js
import * as Sentry from "@sentry/react-router";
import { nodeProfilingIntegration } from "@sentry/profiling-node";

Sentry.init({
  dsn: "https://<key>@o<orgId>.ingest.sentry.io/<projectId>",
  // Enables Profiling
  integrations: [nodeProfilingIntegration()],
  // Enables Tracing.
  // Set to 1.0 to capture 100% of spans for tracing.
  // We recommend reducing this value in production.
  tracesSampleRate: 1.0,
  // Enables Profiling for all sessions.
  // We recommend reducing this value in production.
  profileSessionSampleRate: 1.0,
});
```

Next, replace the default `handleRequest` and `handleError` functions in your `entry.server.tsx` file with Sentry's wrapped versions, and export `instrumentations` to enable automatic tracing.

Exporting `instrumentations` uses React Router's [instrumentation API](https://reactrouter.com/how-to/instrumentation) to automatically create spans for all loaders, actions, middleware, and request handlers — no need to wrap them individually.

```tsx
+import * as Sentry from '@sentry/react-router';
 import { createReadableStreamFromReadable } from '@react-router/node';
 import { renderToPipeableStream } from 'react-dom/server';
 import { ServerRouter } from 'react-router';
 import { type HandleErrorFunction } from 'react-router';

+const handleRequest = Sentry.createSentryHandleRequest({
+  ServerRouter,
+  renderToPipeableStream,
+  createReadableStreamFromReadable,
+});

 export default handleRequest;

+export const handleError = Sentry.createSentryHandleError({
+  logErrors: false
+});

+// Automatically instruments all server loaders, actions, middleware,
+// and request handlers.
+export const instrumentations = [Sentry.createSentryServerInstrumentation()];

// ... rest of your server entry
```

Does your app use Content Security Policy nonces?

If your Node.js app uses a nonce-based Content Security Policy (CSP), pass `getNonce` to `createSentryHandleRequest`. This lets you use your app's per-request nonce without replacing Sentry's request handler or trace meta-tag injection.

Sentry calls `getNonce({ request, loadContext })` once for each rendered request and passes the returned nonce to both `<ServerRouter>` and `renderToPipeableStream`. The callback must return a string or `undefined` synchronously. If you omit it or return `undefined`, the helper doesn't supply a nonce.

For example, if your app uses React Router's `RouterContextProvider`, define a shared context key:

```ts
import { createContext } from "react-router";

export const cspNonceContext = createContext<string>();
```

In your server middleware, generate a fresh, unpredictable nonce for each response, such as with Node.js's `randomBytes(16).toString("base64")`. Store it with `context.set(cspNonceContext, nonce)`, then read it in your server entry:

```tsx
import * as Sentry from "@sentry/react-router";
import { createReadableStreamFromReadable } from "@react-router/node";
import { renderToPipeableStream } from "react-dom/server";
import { RouterContextProvider, ServerRouter } from "react-router";
import { cspNonceContext } from "./context";

const handleRequest = Sentry.createSentryHandleRequest({
  ServerRouter,
  renderToPipeableStream,
  createReadableStreamFromReadable,
  getNonce: ({ loadContext }) =>
    loadContext instanceof RouterContextProvider
      ? loadContext.get(cspNonceContext)
      : undefined,
});

export default handleRequest;

// Keep your existing handleError and instrumentations exports.
```

Without React Router middleware, `loadContext` is your app's `AppLoadContext` instead. Read the nonce from the property where your server stores it.

Your app must also include the **same nonce** in the response's `Content-Security-Policy` header, for example as `'nonce-${nonce}'` in `script-src`. Sentry doesn't generate the nonce or set the CSP header. Don't reuse a nonce across responses or generate a second nonce for the header. See [React Router's CSP guidance](https://reactrouter.com/how-to/security) for details.

Do you need to customize your handleRequest function?

For CSP nonces, use the `getNonce` option described above. If you need other custom rendering logic in your `handleRequest` function, use Sentry's helper functions (`getMetaTagTransformer` and `wrapSentryHandleRequest`) manually:

```tsx
import {
  getMetaTagTransformer,
  wrapSentryHandleRequest,
} from "@sentry/react-router";
// ... other imports

const handleRequest = function handleRequest(
  request: Request,
  responseStatusCode: number,
  responseHeaders: Headers,
  routerContext: EntryContext,
  _loadContext: AppLoadContext,
): Promise<Response> {
  return new Promise((resolve, reject) => {
    let shellRendered = false;
    const userAgent = request.headers.get("user-agent");

    // Determine if we should use onAllReady or onShellReady
    const isBot =
      typeof userAgent === "string" && botRegex.test(userAgent);
    const isSpaMode = !!(routerContext as { isSpaMode?: boolean })
      .isSpaMode;

    const readyOption = isBot || isSpaMode ? "onAllReady" : "onShellReady";

    const { pipe, abort } = renderToPipeableStream(
      <ServerRouter context={routerContext} url={request.url} />,
      {
        [readyOption]() {
          shellRendered = true;
          const body = new PassThrough();

          const stream = createReadableStreamFromReadable(body);

          responseHeaders.set("Content-Type", "text/html");

          resolve(
            new Response(stream, {
              headers: responseHeaders,
              status: responseStatusCode,
            }),
          );

          // this enables distributed tracing between client and server
          pipe(getMetaTagTransformer(body));
        },
        onShellError(error: unknown) {
          reject(error);
        },
        onError(error: unknown) {
          // eslint-disable-next-line no-param-reassign
          responseStatusCode = 500;
          // Log streaming rendering errors from inside the shell.  Don't log
          // errors encountered during initial shell rendering since they'll
          // reject and get logged in handleDocumentRequest.
          if (shellRendered) {
            // eslint-disable-next-line no-console
            console.error(error);
          }
        },
      },
    );

    // Abort the rendering stream after the `streamTimeout`
    setTimeout(abort, streamTimeout);
  });
};

// wrap the default export
export default wrapSentryHandleRequest(handleRequest);

// ... rest of your entry.server.ts file
```

Do you need to customize your handleError function?

If you have custom logic in your `handleError` function, you'll need to capture errors manually:

```tsx
import {
  getMetaTagTransformer,
  wrapSentryHandleRequest,
} from "@sentry/react-router";
// ... other imports

export function handleError(
  error: unknown,
  { request, params, context }: LoaderFunctionArgs | ActionFunctionArgs,
) {
  if (!request.signal.aborted) {
    Sentry.captureException(error);
    console.error(formatErrorForJsonLogging(error));
  }
}

// ... rest of your entry.server.ts file
```

#### [Load Instrumentation on Startup](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#load-instrumentation-on-startup)

React Router runs in ESM mode, which means you need to load the Sentry instrumentation file before the application starts. Update your `package.json` scripts:

```json
"scripts": {
  "dev": "NODE_OPTIONS='--import ./instrument.server.mjs' react-router dev",
  "start": "NODE_OPTIONS='--import ./instrument.server.mjs' react-router-serve ./build/server/index.js",
}
```

Are you using Windows?

If you're on Windows, set the `NODE_OPTIONS` environment variable manually before running your app.

**cmd**

```bash
set NODE_OPTIONS=--import ./instrument.server.mjs
```

**PowerShell**

```powershell
$env:NODE_OPTIONS="--import ./instrument.server.mjs"
```

Read more about [environment variables](https://learn.microsoft.com/en-us/windows/win32/procthread/environment-variables).

**Deploying to Vercel, Netlify, and similar platforms**

If you're deploying to platforms where you can't set the `NODE_OPTIONS` flag, import the instrumentation file directly at the top of your `entry.server.tsx`:

```tsx
+import '../instrument.server';
 import * as Sentry from '@sentry/react-router';
 import { createReadableStreamFromReadable } from '@react-router/node';
 import { renderToPipeableStream } from 'react-dom/server';
 // ... rest of your imports
```

##### Incomplete Auto-instrumentation

When you import the instrumentation file directly instead of using the `--import` flag, automatic instrumentation will be incomplete. You'll miss automatically captured spans and traces for some server-side operations. Only use this approach when the `NODE_OPTIONS` method isn't available.

### [Add Readable Stack Traces With Source Maps](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#add-readable-stack-traces-with-source-maps)

The stack traces in your Sentry errors probably won't look like your actual code without unminifying them. To fix this, upload your source maps to Sentry.

First, update `vite.config.ts` to include the `sentryReactRouter` plugin, making sure to pass both the Vite and Sentry configurations to it:

```typescript
import { reactRouter } from '@react-router/dev/vite';
import { sentryReactRouter, type SentryReactRouterBuildOptions } from '@sentry/react-router/vite';
import { defineConfig } from 'vite';

const sentryConfig: SentryReactRouterBuildOptions = {
  org: "<your-org-slug>",
  project: "<your-project-slug>",

  // An auth token is required for uploading source maps;
  // store it in an environment variable to keep it secure.
  authToken: process.env.SENTRY_AUTH_TOKEN,
  // ...
};

export default defineConfig(config => {
  return {
+   plugins: [reactRouter(),sentryReactRouter(sentryConfig, config)],
  };
});
```

To keep your auth token secure, always store it in an environment variable instead of directly in your files:

```bash
SENTRY_AUTH_TOKEN=<your-sentry-auth-token>
```

Using environment variables in Vite configs

Vite doesn't automatically load `.env` files into `process.env` when evaluating the config file. If you store your auth token in a `.env` file and want to access it via `process.env.SENTRY_AUTH_TOKEN`, use Vite's [`loadEnv`](https://vite.dev/guide/api-javascript#loadenv) helper.

Alternatively, use a `.env.sentry-build-plugin` file, which the Sentry plugin reads automatically.

```javascript
import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");

  return {
    plugins: [
      sentryVitePlugin({
        authToken: env.SENTRY_AUTH_TOKEN,
        // ...
      }),
    ],
  };
});
```

Next, include the `sentryOnBuildEnd` hook in `react-router.config.ts`:

```typescript
import type { Config } from "@react-router/dev/config";
import { sentryOnBuildEnd } from "@sentry/react-router/vite";

export default {
  ssr: true,
  buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => {
    // ...
    // Call this at the end of the hook
+    await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest });
  },
} satisfies Config;
```

### [Control the Data You Send to Sentry](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#control-the-data-you-send-to-sentry)

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](https://docs.sentry.io/platforms/javascript/guides/react-router/configuration/options.md#dataCollection).

```javascript
Sentry.init({
  dsn: "https://<key>@o<orgId>.ingest.sentry.io/<projectId>",
  dataCollection: {
    userInfo: false,
    // other categories
  },
});
```

## [Send Logs](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#send-logs)

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](https://docs.sentry.io/platforms/javascript/guides/react-router/logs.md) for all available logging methods and the syntax for formatting messages.

```javascript
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 already use `console`, capture those calls as Sentry Logs with [`consoleLoggingIntegration`](https://docs.sentry.io/platforms/javascript/guides/react-router/logs.md#console-integration). We also provide integrations for:

* [Consola](https://docs.sentry.io/platforms/javascript/guides/react-router/logs.md#console-integration)
* [Pino](https://docs.sentry.io/platforms/javascript/guides/react-router/configuration/integrations/pino.md)

## [Send Application Metrics NEW](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#send-application-metrics-)

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](https://docs.sentry.io/platforms/javascript/guides/react-router/metrics.md) for all available metric types and configuration options.

```javascript
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" },
});
```

On Node.js, [`nodeRuntimeMetricsIntegration`](https://docs.sentry.io/platforms/javascript/guides/react-router/configuration/integrations/noderuntimemetrics.md) also collects runtime health metrics automatically.

## [Verify Your Setup](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#verify-your-setup)

The `sentry init` command checks the integration files it creates or modifies before it finishes. To confirm runtime events are reaching Sentry, add a test button to your app and click it:

```tsx
<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.

### [View Captured Data in Sentry](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#view-captured-data-in-sentry)

Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear).

Need help locating captured data in your Sentry project?

* Open the [**Issues**](https://sentry.io/orgredirect/organizations/:orgslug/issues/) page and select an error from the issues list to view the full details and context of this error. For more details, see the [Issue Details documentation](https://docs.sentry.io/product/issues/issue-details.md).
* Open the [**Traces**](https://sentry.io/orgredirect/organizations/:orgslug/explore/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](https://docs.sentry.io/product/sentry-basics/getting-started-tutorial/generate-first-error.md#ui-walkthrough).
* Open the [**Profiles**](https://sentry.io/orgredirect/organizations/:orgslug/profiling/) page, select a transaction, and then a profile ID to view its flame graph. For more information, click [here](https://docs.sentry.io/product/profiling/profile-details.md).
* Open the [**Replays**](https://sentry.io/orgredirect/organizations/:orgslug/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.
* Open the [**Logs**](https://sentry.io/orgredirect/organizations/:orgslug/explore/logs/) page and filter by service, environment, or search keywords to view log entries from your application. For an interactive UI walkthrough, click [here](https://docs.sentry.io/product/logs.md#overview).
* Open the [**Application Metrics**](https://sentry.io/orgredirect/organizations/:orgslug/explore/metrics) page to view and analyze your metrics. For more details, see this [interactive walkthrough](https://docs.sentry.io/product/metrics.md#overview).
* Open the [**User Feedback**](https://sentry.io/orgredirect/organizations/:orgslug/feedback/) page and click on individual feedback to see more details all in one view. For more information, click [here](https://docs.sentry.io/product/user-feedback.md).

## [Next Steps](https://docs.sentry.io/platforms/javascript/guides/react-router/manual-setup.md#next-steps)

At this point, you should have integrated Sentry into your React Router Framework application. Here's what to explore next:

* Explore [practical guides](https://docs.sentry.io/get-started/guides.md) on what to monitor, log, track, and investigate after setup
* [Set up tunneling](https://docs.sentry.io/platforms/javascript/guides/react-router/troubleshooting.md#dealing-with-ad-blockers) to avoid ad blockers blocking Sentry events
* [Set up Agent Tracing](https://docs.sentry.io/platforms/javascript/guides/react-router/agent-tracing.md) to monitor your AI systems

Are you having problems setting up the SDK?

* Find various topics in [Troubleshooting](https://docs.sentry.io/platforms/javascript/guides/react-router/troubleshooting.md)
* [Get support](https://www.sentry.help/en/)
