TanStack Start React

Learn how to set up and configure Sentry in your TanStack Start React application, capturing your first errors, and viewing them in Sentry.

This guide walks you through setting up Sentry in a TanStack Start (React) app. For TanStack Router (React), see our React TanStack Router guide.

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.
  • 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 SDK package to your application:

Copied
npm install @sentry/tanstackstart-react --save

Initialize Sentry in your src/router.tsx file:

src/router.tsx
Copied
+import * as Sentry from "@sentry/tanstackstart-react";
 import { createRouter } from '@tanstack/react-router'

// Create a new router instance
export const getRouter = () => {
  const router = createRouter();

+ if (!router.isServer) {
+   Sentry.init({
+     dsn: "",
+
+     // Adds request headers and IP for users, for more info visit:
+     // https://docs.sentry.io/platforms/javascript/guides/tanstackstart-react/configuration/options/#sendDefaultPii
+     sendDefaultPii: true,
+
+     integrations: [
+       //  performance
+       Sentry.tanstackRouterBrowserTracingIntegration(router),
+       //  performance
+       //  session-replay
+       Sentry.replayIntegration(),
+       //  session-replay
+       //  user-feedback
+       Sentry.feedbackIntegration({
+         // Additional SDK configuration goes in here, for example:
+         colorScheme: "system",
+       }),
+       //  user-feedback
+     ],
+     //  logs
+
+     // Enable logs to be sent to Sentry
+     enableLogs: true,
+     //  logs
+
+     //  performance
+     // Set tracesSampleRate to 1.0 to capture 100%
+     // of transactions for tracing.
+     // We recommend adjusting this value in production.
+     // Learn more at https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate
+     tracesSampleRate: 1.0,
+     //  performance
+     //  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,
+     //  session-replay
+   });
  }
  
  return router;
}

Create an instrument file instrument.server.mjs in the root of your project. In this file, initialize the Sentry SDK for your server:

instrument.server.mjs
Copied
import * as Sentry from "@sentry/tanstackstart-react";

Sentry.init({
  dsn: "",

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

  // Enable logs to be sent to Sentry
  enableLogs: true,
  //  logs

  //  performance
  // Set tracesSampleRate to 1.0 to capture 100%
  // of transactions for tracing.
  // We recommend adjusting this value in production
  // Learn more at
  // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate
  tracesSampleRate: 1.0,
  //  performance
});

For production monitoring, you need to move the Sentry server config file to your build output. Since TanStack Start is designed to work with any hosting provider, the exact location will depend on where your build artifacts are deployed (for example, "/dist", ".output/server" or a platform-specific directory).

For example, when using Nitro, copy the instrumentation file to ".output/server":

package.json
Copied
{
  "scripts": {
     "build": "vite build",
     "build": "vite build && cp instrument.server.mjs .output/server",
  }
}

Add a --import flag directly or to the NODE_OPTIONS environment variable wherever you run your application to import instrument.server.mjs.

package.json
Copied
{
  "scripts": {
     "build": "vite build && cp instrument.server.mjs .output/server",
       "dev": "vite dev --port 3000",
       "start": "node .output/server/index.mjs",
       "dev": "NODE_OPTIONS='--import ./instrument.server.mjs' vite dev --port 3000",
       "start": "node --import ./.output/server/instrument.server.mjs .output/server/index.mjs",
  }
}

Sentry automatically captures unhandled client-side errors. Errors caught by your own error boundaries aren't captured unless you report them manually:

Wrap your custom ErrorBoundary component with withErrorBoundary:

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

class MyErrorBoundary extends React.Component {
  // ...
}

export const MySentryWrappedErrorBoundary = Sentry.withErrorBoundary(
  MyErrorBoundary,
  {
    // ... sentry error wrapper options
  },
);

Use Sentry's captureException function inside a useEffect hook within your errorComponent:

Copied
import { createRoute } from "@tanstack/react-router";
import * as Sentry from "@sentry/tanstackstart-react";
const route = createRoute({ errorComponent: ({ error }) => {
useEffect(() => { Sentry.captureException(error) }, [error])
return ( // ... ) } })

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: "",,
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.

To verify that Sentry captures errors and creates issues in your Sentry project, add a 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>;

To test tracing, create a new file like src/routes/api/sentry-example.ts to create a test route /api/sentry-example:

src/routes/api/sentry-example.ts
Copied
import { createFileRoute } from "@tanstack/react-router";
import { json } from "@tanstack/react-start";

export const Route = createFileRoute("/api/sentry-example")({
  server: {
    handlers: {
      GET: () => {
        throw new Error("Sentry Example Route Error");
        return new Response(
          JSON.stringify({ message: "Testing Sentry Error..." }),
          {
            headers: {
              "Content-Type": "application/json",
            },
          },
        );
      },
    },
  },
});

Next, update your test button to call this route and throw an error if the response isn't ok:

Copied
<button
  type="button"
  onClick={async () => {
    await Sentry.startSpan(
      {
        name: "Example Frontend Span",
        op: "test",
      },
      async () => {
        const res = await fetch("/api/sentry-example");
        if (!res.ok) {
          throw new Error("Sentry Example Frontend Error");
        }
      },
    );
  }}
>
  Break the world
</button>;

Open the page in a browser and click the button to trigger two errors:

  • a frontend error
  • an error within the API route

Additionally, this starts a performance trace to measure the time it takes for the API request to complete.

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 TanStack Start 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").