Sentry Integration with React TanStack Router [Typescript]


18 March 2025

Sentry Integration with React TanStack Router [Typescript] using Vite Env Variables and Modes

Sentry provides end-to-end distributed tracing, enabling developers to identify and debug performance issues and errors across their systems and services.

While TanStack Router is a popular React router library, integration with Sentry is not straightforward. This article will guide you through the process of integrating Sentry with TanStack Router.

Prerequisites

Before we begin, ensure you have the following:

  • A Vite project scaffolded with TanStack Router and React.
  • A Sentry DSN

Setting up Sentry

To set up Sentry, follow these steps:

  1. Create a Sentry account if you don’t have one already.
  2. Create a new project and copy the DSN.
  3. Add the Sentry DSN to your environment variables.

Setting up Vite with its Env Variables and Modes

To set up Vite with its enviroment variables and modes, follow these steps:

In your vite-env.d.ts file and by default, import.meta.env has a very broad type, and TypeScript might infer it as any. You can define a more specific type for import.meta.env by extending the ViteEnv type.

Important to note that only variables prefixed with VITE_ are exposed to your Vite-processed code. source: Vite.dev

Let’s declare the types of environment variables we expect:

interface ImportMetaEnv {
  VITE_SENTRY_DSN: string;
  VITE_ENVIRONMENT: "local" | "staging" | "production";
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

Additionally, I’ll create a new file called env.ts in the src directory.

export const env = {
  SENTRY_DSN: import.meta.env.VITE_SENTRY_DSN,
  ENVIRONMENT: import.meta.env.VITE_ENVIRONMENT,
};

Setting up Sentry’s React SDK

To set up Sentry SDK in a react app, follow these steps:

  1. Install the necessary dependencies (assuming you’ve a Vite scaffolded TanStack Router project already set up):
npm  @sentry/react
  1. For my case, I’ve created a new file called sentry.ts in the src directory.
import { env } from "./common/env";
import * as Sentry from "@sentry/react";
import type { Register } from "@tanstack/react-router";

export const initSentry = (router: Register["router"]) => {
  Sentry.init({
    dsn: env.SENTRY_DSN,
    integrations: [Sentry.tanstackRouterBrowserTracingIntegration(router)],
    tracesSampleRate: 1.0,
  });
};
  1. Create a fallback component for the ErrorBoundary:
const ErrorBoundaryFallback = () => {
  return (
    <div>
      <p>An error occurred, please try again in a bit.</p>
    </div>
  );
};

export default ErrorBoundaryFallback;
  1. Let’s say we need to wrap our main route with the Sentry.ErrorBoundary component, we do this by adjusting our main.tsx file (or whatever entry point you have). Import the neccessary libraries/components first
import { initSentry } from "./sentry";
import { createRootRoute, Outlet } from "@tanstack/react-router";
import * as Sentry from "@sentry/react";

// Import the fallback component for the ErrorBoundary
import ErrorBoundaryFallback from "./components/ErrorBoundaryFallback";
  1. Lastly, initialise Sentry by invoking the helper function and wrap your application in a Sentry.ErrorBoundary provider.
// You should already have somthing similar to this
const router = createRouter({
  routeTree,
  defaultPreload: "intent",
});

// Initialize Sentry
initalizeSentry(router);

// Render the app
const rootElement = document.getElementById("root")!;
if (!rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(
    <StrictMode>
      <!-- Wrap it inside Sentry provider -->
      <Sentry.ErrorBoundary fallback={ErrorBoundaryFallback}>
        <RouterProvider router={router} />
      </Sentry.ErrorBoundary>
    </StrictMode>
  );
}