TanStack Start React

Learn how to set up TanStack Start React with Sentry.

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

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

Extend your app's default TanStack Start configuration by adding wrapVinxiConfigWithSentry to your app.config.ts file:

app.config.ts
Copied
import { defineConfig } from "@tanstack/react-start/config";
import { wrapVinxiConfigWithSentry } from "@sentry/tanstackstart-react";

const config = defineConfig({
    // ... your other TanStack Start config
})

export default wrapVinxiConfigWithSentry(config, {
  org: "example-org",
  project: "example-project",
  authToken: process.env.SENTRY_AUTH_TOKEN,

  // Only print logs for uploading source maps in CI
  // Set to `true` to suppress logs
  silent: !process.env.CI,
});

In future versions of this SDK, setting the SENTRY_AUTH_TOKEN environment variable will upload sourcemaps for you to see unminified errors in Sentry:

.env
Copied
SENTRY_AUTH_TOKEN=sntrys_YOUR_TOKEN_HERE

Add the following initialization code to your app/client.tsx file to initialize Sentry on the client:

app/client.tsx
Copied
import { hydrateRoot } from "react-dom/client";
import { StartClient } from "@tanstack/react-start";
import { createRouter } from "./router";

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

const router = createRouter();

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/tanstackstart-react/configuration/options/#sendDefaultPii
  sendDefaultPii: true,

  integrations: [
    //  performance
    Sentry.tanstackRouterBrowserTracingIntegration(router),
    //  performance
    //  session-replay
    Sentry.replayIntegration(),
    //  session-replay
  ],
  //  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
});

hydrateRoot(document, <StartClient router={router} />);

Add the following initialization code anywhere in your app/ssr.tsx file to initialize Sentry on the server:

app/ssr.tsx
Copied
import * as Sentry from "@sentry/tanstackstart-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/tanstackstart-react/configuration/options/#sendDefaultPii
  sendDefaultPii: true,
  //  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
});

Wrap TanStack Start's createRootRoute function using wrapCreateRootRouteWithSentry to apply tracing to Server-Side Rendering (SSR):

app/routes/__root.tsx
Copied
import type { ReactNode } from "react";
import { createRootRoute } from "@tanstack/react-router";
import { wrapCreateRootRouteWithSentry } from "@sentry/tanstackstart-router";
// (Wrap `createRootRoute`, not its return value!)
export const Route = wrapCreateRootRouteWithSentry(createRootRoute)({
// ... });

Wrap TanStack Start's defaultStreamHandler function using wrapStreamHandlerWithSentry to instrument requests to your server:

app/ssr.tsx
Copied
import {
  createStartHandler,
  defaultStreamHandler,
} from "@tanstack/react-start/server";
import { getRouterManifest } from "@tanstack/react-start/router-manifest";
import { createRouter } from "./router";
import * as Sentry from "@sentry/tanstackstart-react";

export default createStartHandler({
  createRouter,
  getRouterManifest,
})(Sentry.wrapStreamHandlerWithSentry(defaultStreamHandler));

Add the sentryGlobalServerMiddlewareHandler to your global middlewares to instrument your server function invocations:

app/global-middleware.ts
Copied
import {
  createMiddleware,
  registerGlobalMiddleware,
} from "@tanstack/react-start";
import * as Sentry from "@sentry/tanstackstart-react";

registerGlobalMiddleware({
  middleware: [
    createMiddleware().server(Sentry.sentryGlobalServerMiddlewareHandler()),
  ],
});

The Sentry SDK cannot capture errors that you manually caught yourself with error boundaries.

If you have React error boundaries in your app and you want to report errors that these boundaries catch to Sentry, apply the withErrorBoundary wrapper to your ErrorBoundary:

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

If you defined errorComponents in your Code-Based TanStack Router routes, capture the error argument with captureException inside a useEffect hook:

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 ( // ... ) } })

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 an existing page or create a new one:

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

To test tracing, create a test API route like /api/sentry-example-api:

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

// A faulty API route to test Sentry's error monitoring
export const APIRoute = createAPIFileRoute("/api/sentry-example-api")({
  GET: ({ request, params }) => {
    throw new Error("Sentry Example API Route Error");
    return json({ message: "Testing Sentry Error..." });
  },
});

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