diff --git a/docs/platforms/javascript/guides/tanstackstart-react/config.yml b/docs/platforms/javascript/guides/tanstackstart-react/config.yml index 6b8e95f99a047..3a42948f68121 100644 --- a/docs/platforms/javascript/guides/tanstackstart-react/config.yml +++ b/docs/platforms/javascript/guides/tanstackstart-react/config.yml @@ -1,5 +1,5 @@ title: TanStack Start React -description: Learn how to set up and configure Sentry in your TanStack Start React application, capturing your first errors, and viewing them in Sentry. +description: Learn how to set up and configure Sentry in your TanStack Start React application using the installation wizard, capturing your first errors, and viewing them in Sentry. sdk: sentry.javascript.tanstackstart-react categories: - javascript diff --git a/docs/platforms/javascript/guides/tanstackstart-react/index.mdx b/docs/platforms/javascript/guides/tanstackstart-react/index.mdx index dfbbdefd16066..ee324eab68d86 100644 --- a/docs/platforms/javascript/guides/tanstackstart-react/index.mdx +++ b/docs/platforms/javascript/guides/tanstackstart-react/index.mdx @@ -1,5 +1,12 @@ --- -title: TanStack Start React +title: "TanStack Start React" +description: Learn how to set up and configure Sentry in your TanStack Start React application using the installation wizard, capture your first errors, logs and traces and view them in Sentry. +sdk: sentry.javascript.tanstackstart-react +categories: + - javascript + - server + - server-node + - browser --- @@ -9,529 +16,44 @@ Please reach out on [GitHub](https://github.com/getsentry/sentry-javascript/issu -This guide walks you through setting up Sentry in a [TanStack Start (React)](https://tanstack.com/start/latest/docs/framework/react/overview) app. -For [TanStack Router (React)](https://tanstack.com/router/latest/docs/framework/react/overview), see our [React TanStack Router guide](/platforms/javascript/guides/react/features/tanstack-router). + - + ## Install -Choose the features you want to configure, and this guide will show you how: - - - - - -### Install the Sentry SDK - - - - - -Run the command for your preferred package manager to add the SDK package to your application: - - - - -```bash {tabTitle:npm} -npm install @sentry/tanstackstart-react --save -``` - -```bash {tabTitle:yarn} -yarn add @sentry/tanstackstart-react -``` - -```bash {tabTitle:pnpm} -pnpm add @sentry/tanstackstart-react -``` - - - - - -## Configure - -### Configure Client-Side Sentry - - - - - -Initialize Sentry in your `src/router.tsx` file: - - - - -```tsx {diff} {filename: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; -} -``` - - - - - -### Configure Server-Side Sentry - - - - - -Create an instrument file `instrument.server.mjs` in the root of your project. In this file, initialize the Sentry SDK for your server: - - - - -```tsx {filename:instrument.server.mjs} -import * 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 -}); -``` - - - - - -#### Add the sentryTanstackStart Vite Plugin - - - - - -Configure `sentryTanstackStart` in your `vite.config.ts`. - -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](/platforms/javascript/guides/tanstackstart-react/features/sentryTanstackStart/). - - - - -```typescript {filename:vite.config.ts} -import { 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, - }), - ], -}); -``` - - - - - - - - - -To keep your auth token secure, always store it in an environment variable instead of directly in your files: - - - Make sure to add your auth token to your CI, if you're using one to deploy - your application. - - - - - - -```bash {filename:.env} -SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ -``` - - - - - - - -#### Instrument the Server Entry Point - -To capture server-side errors and tracing data, you need to explicitly define a [server entry point](https://tanstack.com/start/latest/docs/framework/react/guide/server-entry-point) in your application and wrap your request handler with `wrapFetchWithSentry`. - -Follow the section below that matches your deployment setup: - -#### With `--import` Flag (e.g. Node.js Server) - -Use this setup when you can configure Node.js CLI flags. - - - - - -Create a `src/server.ts` file in your project: - - - - -```typescript {filename:src/server.ts} -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); - }, - }) -); -``` - - - - - -##### Move the Sentry Server Config File for Production Usage - - - - - -For production monitoring, you need to move the Sentry server config file to your build output. The exact location depends 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"` as shown in the example on the right. - - - - -```json {diff} {filename:package.json} -{ - "scripts": { -- "build": "vite build", -+ "build": "vite build && cp instrument.server.mjs .output/server", - } -} -``` - - - - - -##### Load Instrumentation on Startup - - - - - -To load `instrument.server.mjs`, add the `--import` flag either directly to your run command or to the `NODE_OPTIONS` environment variable. - - - - -```json {diff} {filename: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", - } -} -``` - - - - - -#### Without `--import` Flag - -Use this setup when 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 only instrument native Node.js APIs (such as `fetch` and the `http` module) with this installation method. -This means that the Sentry SDK will not capture data from database calls, queues, ORMs, third-party libraries, or other framework-specific data. -Thus, we recommend you follow the [`--import` flag setup instructions](#with---import-flag-eg-nodejs-server) if possible. - -This setup doesn't work for Cloudflare deployments. - - - - - - - -Create a `src/server.ts` file in your project and import the server instrumentation file directly at the top of your server entry point. - - - - -```typescript {filename:src/server.ts} -import "../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); - }, - }) -); -``` - - - - - -### Capture TanStack Start React Errors - -#### Capture Server-Side Errors - - - - - -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. + -The Sentry middleware should be the first middleware in the arrays to ensure all errors are captured. +The wizard is currently experimental. If you run into any issues, check out the [Manual Setup](/platforms/javascript/guides/tanstackstart-react/manual-setup/) guide. - - SSR rendering exceptions are not captured by the middleware. Use - `captureException` to manually capture those errors. - - - -```tsx {filename:src/start.ts} -import { - sentryGlobalFunctionMiddleware, - sentryGlobalRequestMiddleware, -} from "@sentry/tanstackstart-react"; -import { createStart } from "@tanstack/react-start"; - -export const startInstance = createStart(() => { - return { - requestMiddleware: [sentryGlobalRequestMiddleware], - functionMiddleware: [sentryGlobalFunctionMiddleware], - }; -}); -``` - - - - - -#### Capture Errors in Error Boundaries and Components (Optional) - -Sentry automatically captures unhandled client-side errors. Errors caught by your own error boundaries aren't captured unless you report them manually: - -##### Custom Error Boundary - - - - - -Wrap your custom `ErrorBoundary` component with [`withErrorBoundary`](/platforms/javascript/guides/react/features/error-boundary/): - - - - -```tsx -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 - } -); -``` - - - - - -##### TanStack Router `errorComponent` - - - - - -Use Sentry's `captureException` function inside a `useEffect` hook within your `errorComponent`: - - - - -```tsx {2,6-8} -import { createRoute } from "@tanstack/react-router"; -import * as Sentry from "@sentry/tanstackstart-react"; - -const route = createRoute({ - errorComponent: ({ error }) => { - useEffect(() => { - Sentry.captureException(error) - }, [error]) - - return ( - // ... - ) - } -}) -``` - - - - - -### Add Readable Stack Traces With Source Maps (Optional) - -If you configured the `sentryTanstackStart` Vite plugin [in an earlier step](#add-the-sentrytanstackstart-vite-plugin), source maps are automatically uploaded during production builds. +Run the Sentry init command to automatically configure Sentry in your TanStack Start React application: -If you need more control over the upload process, see our [source maps guide](/platforms/javascript/guides/tanstackstart-react/sourcemaps/) for manual configuration options. - -### Avoid Ad Blockers With Tunneling (Optional) - - - - - -Ad blockers and corporate firewalls often block requests to `*.sentry.io`, which can cause events to be dropped before they reach Sentry. To work around this, you can tunnel events through a same-origin route in your TanStack Start app. - -The `sentryTanstackStart` Vite plugin can register a tunnel route for you and automatically wire up the client `tunnel` option. - -Setting `tunnelRoute: true` generates an opaque route for each dev session and production build, making it harder for ad blockers to target. See the [`sentryTanstackStart`](/platforms/javascript/guides/tanstackstart-react/features/sentryTanstackStart/#tunnel-route) feature page for static paths and the full set of options. - -If you can't use the Vite plugin, or need full control over the route file and DSN allowlist, use [`createSentryTunnelRoute`](/platforms/javascript/guides/tanstackstart-react/features/createSentryTunnelRoute/) to define the route yourself. - - - - -```typescript {filename:vite.config.ts} {9} -import { defineConfig } from "vite"; -import { tanstackStart } from "@tanstack/react-start/plugin/vite"; -import { sentryTanstackStart } from "@sentry/tanstackstart-react/vite"; - -export default defineConfig({ - plugins: [ - tanstackStart(), - sentryTanstackStart({ - tunnelRoute: true, - }), - ], -}); +```bash +npx sentry@latest init ``` - - - - -## Verify +## How It Works -Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. +The Sentry init wizard is AI-powered — it analyzes your project and generates a tailored integration, rather than applying a fixed template. Here's what it does: -### Issues +- **Analyzes your project** — reads your project's files and manifests to understand its structure, including monorepos. It also respects any AI instruction files you have (`CLAUDE.md`, `AGENTS.md`, `.cursorrules`, etc.). +- **Detects your framework** — identifies TanStack Start and selects the right SDK (`@sentry/tanstackstart-react`) +- **Fetches official Sentry docs** — uses the current Sentry documentation as the source of truth when generating your integration code, so you always get up-to-date setup +- **Installs dependencies** — adds `@sentry/tanstackstart-react` using your project's package manager +- **Creates and modifies files** — sets up client-side and server-side initialization, the Vite plugin for source maps, the server entry point, and middleware — all adapted to your project's structure +- **Verifies the integration** — re-reads the modified files after writing to confirm Sentry was correctly integrated - - - +For full details on what each file does, see the [Manual Setup](/platforms/javascript/guides/tanstackstart-react/manual-setup/) guide. -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. - - - Then, open the page in a browser and click the button to trigger a frontend - error. - +## Verify Your Setup - - +Add a test button to one of your pages to trigger an error: ```tsx -``` + - - - +**Session Replay** — [Open Replays](https://sentry.io/orgredirect/organizations/:orgslug/replays/) + +Watch a video-like recording of your session, including the moment the error occurred. Learn more about [Session Replay configuration](/platforms/javascript/guides/tanstackstart-react/session-replay/). - +**Logs** — [Open Logs](https://sentry.io/orgredirect/organizations/:orgslug/explore/logs/) + +See structured log entries from your application. You can send logs from anywhere: + +```typescript +Sentry.logger.info("User action", { userId: "123" }); +Sentry.logger.warn("Slow response", { duration: 5000 }); +Sentry.logger.error("Operation failed", { reason: "timeout" }); +``` + +Learn more about [Logs configuration](/platforms/javascript/guides/tanstackstart-react/logs/). -### 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). +- If you encountered issues with the installation wizard, try [setting up Sentry manually](/platforms/javascript/guides/tanstackstart-react/manual-setup/) +- Check [Troubleshooting](/platforms/javascript/guides/tanstackstart-react/troubleshooting/) for common issues +- [Get support](https://sentry.zendesk.com/hc/en-us/) - + ## Next Steps -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: +You've successfully integrated Sentry into your TanStack Start React application! Here's what to explore next: - Explore [practical guides](/guides/) on what to monitor, log, track, and investigate after setup - Learn how to [manually capture errors](/platforms/javascript/guides/tanstackstart-react/usage/) - Continue to [customize your configuration](/platforms/javascript/guides/tanstackstart-react/configuration/) - Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts - - -- Find various topics in Troubleshooting -- [Get support](https://sentry.zendesk.com/hc/en-us/) - - - - + diff --git a/docs/platforms/javascript/guides/tanstackstart-react/manual-setup/index.mdx b/docs/platforms/javascript/guides/tanstackstart-react/manual-setup/index.mdx new file mode 100644 index 0000000000000..852f20feb082f --- /dev/null +++ b/docs/platforms/javascript/guides/tanstackstart-react/manual-setup/index.mdx @@ -0,0 +1,676 @@ +--- +title: "Manual Setup" +sidebar_order: 1 +description: Learn how to manually set up and configure Sentry in your TanStack Start React application, capturing your first errors, and viewing them in Sentry. +sdk: sentry.javascript.tanstackstart-react +categories: + - javascript + - server + - server-node + - browser +--- + + + +For the fastest setup, we recommend using the [installation wizard](/platforms/javascript/guides/tanstackstart-react/). + + + + + +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](https://github.com/getsentry/sentry-javascript/issues/new/choose) if you have any feedback or concerns. + + + +This guide walks you through setting up Sentry in a [TanStack Start (React)](https://tanstack.com/start/latest/docs/framework/react/overview) app. +For [TanStack Router (React)](https://tanstack.com/router/latest/docs/framework/react/overview), see our [React TanStack Router guide](/platforms/javascript/guides/react/features/tanstack-router). + + + + + +## Install + +Choose the features you want to configure, and this guide will show you how: + + + + + +### Install the Sentry SDK + + + + + +Run the command for your preferred package manager to add the SDK package to your application: + + + + +```bash {tabTitle:npm} +npm install @sentry/tanstackstart-react --save +``` + +```bash {tabTitle:yarn} +yarn add @sentry/tanstackstart-react +``` + +```bash {tabTitle:pnpm} +pnpm add @sentry/tanstackstart-react +``` + + + + + +## Configure + +### Configure Client-Side Sentry + + + + + +Initialize Sentry in your `src/router.tsx` file: + + + + +```tsx {diff} {filename: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; +} +``` + + + + + +### Configure Server-Side Sentry + + + + + +Create an instrument file `instrument.server.mjs` in the root of your project. In this file, initialize the Sentry SDK for your server: + + + + +```tsx {filename:instrument.server.mjs} +import * 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 +}); +``` + + + + + +#### Add the sentryTanstackStart Vite Plugin + + + + + +Configure `sentryTanstackStart` in your `vite.config.ts`. + +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](/platforms/javascript/guides/tanstackstart-react/features/sentryTanstackStart/). + + + + +```typescript {filename:vite.config.ts} +import { 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, + }), + ], +}); +``` + + + + + + + + + +To keep your auth token secure, always store it in an environment variable instead of directly in your files: + + + Make sure to add your auth token to your CI, if you're using one to deploy + your application. + + + + + + +```bash {filename:.env} +SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ +``` + + + + + + + +#### Instrument the Server Entry Point + +To capture server-side errors and tracing data, you need to explicitly define a [server entry point](https://tanstack.com/start/latest/docs/framework/react/guide/server-entry-point) in your application and wrap your request handler with `wrapFetchWithSentry`. + +Follow the section below that matches your deployment setup: + +#### With `--import` Flag (e.g. Node.js Server) + +Use this setup when you can configure Node.js CLI flags. + + + + + +Create a `src/server.ts` file in your project: + + + + +```typescript {filename:src/server.ts} +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); + }, + }) +); +``` + + + + + +##### Move the Sentry Server Config File for Production Usage + + + + + +For production monitoring, you need to move the Sentry server config file to your build output. The exact location depends 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"` as shown in the example on the right. + + + + +```json {diff} {filename:package.json} +{ + "scripts": { +- "build": "vite build", ++ "build": "vite build && cp instrument.server.mjs .output/server", + } +} +``` + + + + + +##### Load Instrumentation on Startup + + + + + +To load `instrument.server.mjs`, add the `--import` flag either directly to your run command or to the `NODE_OPTIONS` environment variable. + + + + +```json {diff} {filename: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", + } +} +``` + + + + + +#### Without `--import` Flag + +Use this setup when 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 only instrument native Node.js APIs (such as `fetch` and the `http` module) with this installation method. +This means that the Sentry SDK will not capture data from database calls, queues, ORMs, third-party libraries, or other framework-specific data. +Thus, we recommend you follow the [`--import` flag setup instructions](#with---import-flag-eg-nodejs-server) if possible. + +This setup doesn't work for Cloudflare deployments. + + + + + + + +Create a `src/server.ts` file in your project and import the server instrumentation file directly at the top of your server entry point. + + + + +```typescript {filename:src/server.ts} +import "../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); + }, + }) +); +``` + + + + + +### Capture TanStack Start React Errors + +#### Capture Server-Side Errors + + + + + +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. + +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. + + + + + +```tsx {filename:src/start.ts} +import { + sentryGlobalFunctionMiddleware, + sentryGlobalRequestMiddleware, +} from "@sentry/tanstackstart-react"; +import { createStart } from "@tanstack/react-start"; + +export const startInstance = createStart(() => { + return { + requestMiddleware: [sentryGlobalRequestMiddleware], + functionMiddleware: [sentryGlobalFunctionMiddleware], + }; +}); +``` + + + + + +#### Capture Errors in Error Boundaries and Components (Optional) + +Sentry automatically captures unhandled client-side errors. Errors caught by your own error boundaries aren't captured unless you report them manually: + +##### Custom Error Boundary + + + + + +Wrap your custom `ErrorBoundary` component with [`withErrorBoundary`](/platforms/javascript/guides/react/features/error-boundary/): + + + + +```tsx +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 + } +); +``` + + + + + +##### TanStack Router `errorComponent` + + + + + +Use Sentry's `captureException` function inside a `useEffect` hook within your `errorComponent`: + + + + +```tsx {2,6-8} +import { createRoute } from "@tanstack/react-router"; +import * as Sentry from "@sentry/tanstackstart-react"; + +const route = createRoute({ + errorComponent: ({ error }) => { + useEffect(() => { + Sentry.captureException(error) + }, [error]) + + return ( + // ... + ) + } +}) +``` + + + + + +### Add Readable Stack Traces With Source Maps (Optional) + +If you configured the `sentryTanstackStart` Vite plugin [in an earlier step](#add-the-sentrytanstackstart-vite-plugin), source maps are automatically uploaded during production builds. + +If you need more control over the upload process, see our [source maps guide](/platforms/javascript/guides/tanstackstart-react/sourcemaps/) for manual configuration options. + +### Avoid Ad Blockers With Tunneling (Optional) + + + + + +Ad blockers and corporate firewalls often block requests to `*.sentry.io`, which can cause events to be dropped before they reach Sentry. To work around this, you can tunnel events through a same-origin route in your TanStack Start app. + +The `sentryTanstackStart` Vite plugin can register a tunnel route for you and automatically wire up the client `tunnel` option. + +Setting `tunnelRoute: true` generates an opaque route for each dev session and production build, making it harder for ad blockers to target. See the [`sentryTanstackStart`](/platforms/javascript/guides/tanstackstart-react/features/sentryTanstackStart/#tunnel-route) feature page for static paths and the full set of options. + +If you can't use the Vite plugin, or need full control over the route file and DSN allowlist, use [`createSentryTunnelRoute`](/platforms/javascript/guides/tanstackstart-react/features/createSentryTunnelRoute/) to define the route yourself. + + + + +```typescript {filename:vite.config.ts} {9} +import { defineConfig } from "vite"; +import { tanstackStart } from "@tanstack/react-start/plugin/vite"; +import { sentryTanstackStart } from "@sentry/tanstackstart-react/vite"; + +export default defineConfig({ + plugins: [ + tanstackStart(), + sentryTanstackStart({ + tunnelRoute: true, + }), + ], +}); +``` + + + + + +## Verify + +Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. + +### Issues + + + + + +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. + + + Then, open the page in a browser and click the button to trigger a frontend + error. + + + + + + + +```tsx + +``` + + + + + + +### Tracing + + + + + +To test tracing, create a new file like `src/routes/api/sentry-example.ts` to create a test route `/api/sentry-example`: + + + + +```typescript {filename:src/routes/api/sentry-example.ts} +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`. + +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. + + + + +```tsx + +``` + + + + + + + + + + + + + +### 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). + + + +## Next Steps + +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](/guides/) on what to monitor, log, track, and investigate after setup +- Learn how to [manually capture errors](/platforms/javascript/guides/tanstackstart-react/usage/) +- Continue to [customize your configuration](/platforms/javascript/guides/tanstackstart-react/configuration/) +- Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts + + + +- Find various topics in Troubleshooting +- [Get support](https://sentry.zendesk.com/hc/en-us/) + + + + diff --git a/platform-includes/llm-rules-platform/javascript.tanstackstart-react.mdx b/platform-includes/llm-rules-platform/javascript.tanstackstart-react.mdx new file mode 100644 index 0000000000000..3c13a7ab81a05 --- /dev/null +++ b/platform-includes/llm-rules-platform/javascript.tanstackstart-react.mdx @@ -0,0 +1 @@ +