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 SDK is compatible with TanStack Start 1.0 RC and is currently in ALPHA. Alpha features are still in progress, may have bugs and might include breaking changes. Please reach out on GitHub if you have any feedback or concerns.
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:
Run the command for your preferred package manager to add the SDK package to your application:
npm install @sentry/tanstackstart-react --save
Initialize Sentry in your src/router.tsx file:
src/router.tsx+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: "___PUBLIC_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: [
+ // ___PRODUCT_OPTION_START___ performance
+ Sentry.tanstackRouterBrowserTracingIntegration(router),
+ // ___PRODUCT_OPTION_END___ performance
+ // ___PRODUCT_OPTION_START___ session-replay
+ Sentry.replayIntegration(),
+ // ___PRODUCT_OPTION_END___ session-replay
+ // ___PRODUCT_OPTION_START___ user-feedback
+ Sentry.feedbackIntegration({
+ // Additional SDK configuration goes in here, for example:
+ colorScheme: "system",
+ }),
+ // ___PRODUCT_OPTION_END___ user-feedback
+ ],
+ // ___PRODUCT_OPTION_START___ logs
+
+ // Enable logs to be sent to Sentry
+ enableLogs: true,
+ // ___PRODUCT_OPTION_END___ logs
+
+ // ___PRODUCT_OPTION_START___ 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,
+ // ___PRODUCT_OPTION_END___ performance
+ // ___PRODUCT_OPTION_START___ 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,
+ // ___PRODUCT_OPTION_END___ 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.mjsimport * as Sentry from "@sentry/tanstackstart-react";
Sentry.init({
dsn: "___PUBLIC_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,
// ___PRODUCT_OPTION_START___ logs
// Enable logs to be sent to Sentry
enableLogs: true,
// ___PRODUCT_OPTION_END___ logs
// ___PRODUCT_OPTION_START___ 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,
// ___PRODUCT_OPTION_END___ performance
});
Make sure you add your auth token to your CI, if you are using one to deploy your application.
Add your auth token to your environment:
.envSENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___
and configure sentryTanstackStart in your vite.config.ts:
vite.config.tsimport { defineConfig } from "vite";
import { sentryTanstackStart } from "@sentry/tanstackstart-react/vite";
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
export default defineConfig({
plugins: [
tanstackStart(),
// other plugins - sentryTanstackStart should be last
sentryTanstackStart({
org: "___ORG_SLUG___",
project: "___PROJECT_SLUG___",
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
});
By default, this plugin manages source map uploads. When tracing is enabled, it also automatically instruments middlewares for tracing. For all available options, see the Vite Plugin documentation.
To capture server-side errors and tracing data, you need to explicitly define a server entry point in your application and wrap your request handler with wrapFetchWithSentry.
Follow the section below that matches your deployment setup:
Use this setup when you can configure Node.js CLI flags.
Create a src/server.ts file in your project:
src/server.tsimport { wrapFetchWithSentry } from "@sentry/tanstackstart-react";
import handler, {
createServerEntry,
} from "@tanstack/react-start/server-entry";
export default createServerEntry(
wrapFetchWithSentry({
fetch(request: Request) {
return handler.fetch(request);
},
}),
);
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{
"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{
"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",
}
}
If you can't configure Node.js CLI flags or environment variables at runtime (for example, when deploying to serverless platforms like Vercel or Netlify), you can import the server instrumentation file directly at the top of your server entry point instead.
Create a src/server.ts file in your project:
src/server.tsimport "../instrument.server.mjs";
import { wrapFetchWithSentry } from "@sentry/tanstackstart-react";
import handler, {
createServerEntry,
} from "@tanstack/react-start/server-entry";
export default createServerEntry(
wrapFetchWithSentry({
fetch(request: Request) {
return handler.fetch(request);
},
}),
);
Restrictions of this installation method
This installation method has the fundamental restriction that only native Node.js APIs can be instrumented (such as fetch and the http module).
As a result, the Sentry SDK will not capture data from database calls, queues, ORMs, third-party libraries, or other framework-specific data.
We recommend using the setup with the --import flag if possible.
This setup does not currently work for Cloudflare deployments.
To capture server-side errors from HTTP requests and server function calls, add Sentry's global middlewares to createStart() in your src/start.ts file:
src/start.tsimport {
sentryGlobalFunctionMiddleware,
sentryGlobalRequestMiddleware,
} from "@sentry/tanstackstart-react";
import { createStart } from "@tanstack/react-start";
export const startInstance = createStart(() => {
return {
requestMiddleware: [sentryGlobalRequestMiddleware],
functionMiddleware: [sentryGlobalFunctionMiddleware],
};
});
The Sentry middleware should be the first middleware in the arrays to ensure all errors are captured.
SSR rendering exceptions are not captured by the middleware. Use captureException to manually capture those errors.
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:
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:
import { createRoute } from "@tanstack/react-router";
import * as Sentry from "@sentry/tanstackstart-react";
const route = createRoute({
errorComponent: ({ error }) => {
useEffect(() => {
Sentry.captureException(error)
}, [error])
return (
// ...
)
}
})
If you configured the sentryTanstackStart Vite plugin in Step 2, source maps are automatically uploaded during production builds.
If you need more control over the upload process, see our source maps guide for manual configuration options.
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:
Sentry.init({
dsn: "___PUBLIC_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:
<button
type="button"
onClick={() => {
throw new Error("Sentry Test Error");
}}
>
Break the world
</button>;
Open the page in a browser and click the button to trigger a frontend error.
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.
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.tsimport { 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:
<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).
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:
- Explore practical guides on what to monitor, log, track, and investigate after setup
- Learn how to manually capture errors
- Continue to customize your configuration
- Get familiar with Sentry's product features like tracing, insights, and alerts
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").