Open History to see the last commit
1---
2id: observability
3title: Observability
4---
5β
6Observability is a critical aspect of modern web development, enabling you to monitor, trace, and debug your application's performance and errors. TanStack Start provides built-in patterns for observability and integrates seamlessly with external tools to give you comprehensive insights into your application.
7β
8## Partner Solution: Sentry
9β
10<a href="https://sentry.io?utm_source=tanstack" alt='Sentry Logo'>
11 <picture>
12 <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/tanstack/tanstack.com/main/src/images/sentry-wordmark-light.svg" width="280">
13 <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/tanstack/tanstack.com/main/src/images/sentry-wordmark-dark.svg" width="280">
14 <img alt="Sentry logo" src="https://raw.githubusercontent.com/tanstack/tanstack.com/main/src/images/sentry-wordmark-light.svg" width="280">
15 </picture>
16</a>
17β
18For comprehensive observability, we recommend [Sentry](https://sentry.io?utm_source=tanstack) - our trusted partner for error tracking and performance monitoring. Sentry provides:
19β
20- **Real-time Error Tracking** - Catch and debug errors across your entire stack
21- **Performance Monitoring** - Track slow transactions and optimize bottlenecks
22- **Release Health** - Monitor deployments and track error rates over time
23- **User Impact Analysis** - Understand how errors affect your users
24- **TanStack Start Integration** - Works seamlessly with server functions and client code
25β
26**Quick Setup:**
27β
28```tsx
29// Client-side (app.tsx)
30import * as Sentry from '@sentry/react'
31β
32Sentry.init({
33 dsn: import.meta.env.VITE_SENTRY_DSN,
34 environment: import.meta.env.NODE_ENV,
35})
36β
37// Server functions
38import * as Sentry from '@sentry/node'
39β
40const serverFn = createServerFn().handler(async () => {
41 try {
42 return await riskyOperation()
43 } catch (error) {
44 Sentry.captureException(error)
45 throw error
46 }
47})
48```
49β
50[Get started with Sentry β](https://sentry.io/signup?utm_source=tanstack) | [View integration example β](https://github.com/TanStack/router/tree/main/e2e/react-router/sentry-integration)
51β
52## Built-in Observability Patterns
53β
54TanStack Start's architecture provides several opportunities for built-in observability without external dependencies:
55β
56### Server Function Logging
57β
58Add logging to your server functions to track execution, performance, and errors:
59β
60```tsx
61import { createServerFn } from '@tanstack/react-start'
62β
63const getUser = createServerFn({ method: 'GET' })
64 .validator((id: string) => id)
65 .handler(async ({ data: id }) => {
66 const startTime = Date.now()
67β
68 try {
69 console.log(`[SERVER] Fetching user ${id}`)
70β
71 const user = await db.users.findUnique({ where: { id } })
72β
73 if (!user) {
74 console.log(`[SERVER] User ${id} not found`)
75 throw new Error('User not found')
76 }
77β
78 const duration = Date.now() - startTime
79 console.log(`[SERVER] User ${id} fetched in ${duration}ms`)
80β
81 return user
82 } catch (error) {
83 const duration = Date.now() - startTime
84 console.error(
85 `[SERVER] Error fetching user ${id} after ${duration}ms:`,
86 error,
87 )
88 throw error
89 }
90 })
91```
92β
93### Request/Response Middleware
94β
95Create middleware to log all requests and responses:
96β
97```tsx
98import { createMiddleware } from '@tanstack/react-start'
99β
100const requestLogger = createMiddleware().server(async ({ request, next }) => {
101 const startTime = Date.now()
102 const timestamp = new Date().toISOString()
103β
104 console.log(`[${timestamp}] ${request.method} ${request.url} - Starting`)
105β
106 try {
107 const result = await next()
108 const duration = Date.now() - startTime
109β
110 console.log(
111 `[${timestamp}] ${request.method} ${request.url} - ${result.response.status} (${duration}ms)`,
112 )
113β
114 return result
115 } catch (error) {
116 const duration = Date.now() - startTime
117 console.error(
118 `[${timestamp}] ${request.method} ${request.url} - Error (${duration}ms):`,
119 error,
120 )
121 throw error
122 }
123})
124β
125// Apply to all server routes
126export const Route = createFileRoute('/api/users')({
127 server: {
128 middleware: [requestLogger],
129 handlers: {
130 GET: async () => {
131 return Response.json({ users: await getUsers() })
132 },
133 },
134 },
135})
136```
137β
138### Route Performance Monitoring
139β
140Track route loading performance on both client and server:
141β
142```tsx
143import { createFileRoute } from '@tanstack/react-router'
144β
145export const Route = createFileRoute('/dashboard')({
146 loader: async ({ context }) => {
147 const startTime = Date.now()
148β
149 try {
150 const data = await loadDashboardData()
151 const duration = Date.now() - startTime
152β
153 // Log server-side performance
154 if (typeof window === 'undefined') {
155 console.log(`[SSR] Dashboard loaded in ${duration}ms`)
156 }
157β
158 return data
159 } catch (error) {
160 const duration = Date.now() - startTime
161 console.error(`[LOADER] Dashboard error after ${duration}ms:`, error)
162 throw error
163 }
164 },
165 component: Dashboard,
166})
167β
168function Dashboard() {
169 const data = Route.useLoaderData()
170β
171 // Track client-side render time
172 React.useEffect(() => {
173 const renderTime = performance.now()
174 console.log(`[CLIENT] Dashboard rendered in ${renderTime}ms`)
175 }, [])
176β
177 return <div>Dashboard content</div>
178}
179```
180β
181### Health Check Endpoints
182β
183Create server routes for health monitoring:
184β
185```tsx
186// routes/health.ts
187import { createFileRoute } from '@tanstack/react-router'
188β
189export const Route = createFileRoute('/health')({
190 server: {
191 handlers: {
192 GET: async () => {
193 const checks = {
194 status: 'healthy',
195 timestamp: new Date().toISOString(),
196 uptime: process.uptime(),
197 memory: process.memoryUsage(),
198 database: await checkDatabase(),
199 version: process.env.npm_package_version,
200 }
201β
202 return Response.json(checks)
203 },
204 },
205 },
206})
207β
208async function checkDatabase() {
209 try {
210 await db.raw('SELECT 1')
211 return { status: 'connected', latency: 0 }
212 } catch (error) {
213 return { status: 'error', error: error.message }
214 }
215}
216```
217β
218### Error Boundaries
219β
220Implement comprehensive error handling:
221β
222```tsx
223// Client-side error boundary
224import { ErrorBoundary } from 'react-error-boundary'
225β
226function ErrorFallback({ error, resetErrorBoundary }: any) {
227 // Log client errors
228 console.error('[CLIENT ERROR]:', error)
229β
230 // Could also send to external service
231 // sendErrorToService(error)
232β
233 return (
234 <div role="alert">
235 <h2>Something went wrong</h2>
236 <button onClick={resetErrorBoundary}>Try again</button>
237 </div>
238 )
239}
240β
241export function App() {
242 return (
243 <ErrorBoundary FallbackComponent={ErrorFallback}>
244 <Router />
245 </ErrorBoundary>
246 )
247}
248β
249// Server function error handling
250const riskyOperation = createServerFn().handler(async () => {
251 try {
252 return await performOperation()
253 } catch (error) {
254 // Log server errors with context
255 console.error('[SERVER ERROR]:', {
256 error: error.message,
257 stack: error.stack,
258 timestamp: new Date().toISOString(),
259 // Add request context if available
260 })
261β
262 // Return user-friendly error
263 throw new Error('Operation failed. Please try again.')
264 }
265})
266```
267β
268### Performance Metrics Collection
269β
270Collect and expose basic performance metrics:
271β
272```tsx
273// utils/metrics.ts
274class MetricsCollector {
275 private metrics = new Map<string, number[]>()
276β
277 recordTiming(name: string, duration: number) {
278 if (!this.metrics.has(name)) {
279 this.metrics.set(name, [])
280 }
281 this.metrics.get(name)!.push(duration)
282 }
283β
284 getStats(name: string) {
285 const timings = this.metrics.get(name) || []
286 if (timings.length === 0) return null
287β
288 const sorted = timings.sort((a, b) => a - b)
289 return {
290 count: timings.length,
291 avg: timings.reduce((a, b) => a + b, 0) / timings.length,
292 p50: sorted[Math.floor(sorted.length * 0.5)],
293 p95: sorted[Math.floor(sorted.length * 0.95)],
294 min: sorted[0],
295 max: sorted[sorted.length - 1],
296 }
297 }
298β
299 getAllStats() {
300 const stats: Record<string, any> = {}
301 for (const [name] of this.metrics) {
302 stats[name] = this.getStats(name)
303 }
304 return stats
305 }
306}
307β
308export const metrics = new MetricsCollector()
309β
310// Metrics endpoint
311// routes/metrics.ts
312export const Route = createFileRoute('/metrics')({
313 server: {
314 handlers: {
315 GET: async () => {
316 return Response.json({
317 system: {
318 uptime: process.uptime(),
319 memory: process.memoryUsage(),
320 timestamp: new Date().toISOString(),
321 },
322 application: metrics.getAllStats(),
323 })
324 },
325 },
326 },
327})
328```
329β
330### Debug Headers for Development
331β
332Add helpful debug information to responses:
333β
334```tsx
335import { createMiddleware } from '@tanstack/react-start'
336β
337const debugMiddleware = createMiddleware().server(async ({ next }) => {
338 const result = await next()
339β
340 if (process.env.NODE_ENV === 'development') {
341 result.response.headers.set('X-Debug-Timestamp', new Date().toISOString())
342 result.response.headers.set('X-Debug-Node-Version', process.version)
343 result.response.headers.set('X-Debug-Uptime', process.uptime().toString())
344 }
345β
346 return result
347})
348```
349β
350### Environment-Specific Logging
351β
352Configure different logging strategies for development vs production:
353β
354```tsx
355// utils/logger.ts
356import { createIsomorphicFn } from '@tanstack/react-start'
357β
358type LogLevel = 'debug' | 'info' | 'warn' | 'error'
359β
360const logger = createIsomorphicFn()
361 .server((level: LogLevel, message: string, data?: any) => {
362 const timestamp = new Date().toISOString()
363β
364 if (process.env.NODE_ENV === 'development') {
365 // Development: Detailed console logging
366 console[level](`[${timestamp}] [${level.toUpperCase()}]`, message, data)
367 } else {
368 // Production: Structured JSON logging
369 console.log(
370 JSON.stringify({
371 timestamp,
372 level,
373 message,
374 data,
375 service: 'tanstack-start',
376 environment: process.env.NODE_ENV,
377 }),
378 )
379 }
380 })
381 .client((level: LogLevel, message: string, data?: any) => {
382 if (process.env.NODE_ENV === 'development') {
383 console[level](`[CLIENT] [${level.toUpperCase()}]`, message, data)
384 } else {
385 // Production: Send to analytics service
386 // analytics.track('client_log', { level, message, data })
387 }
388 })
389β
390// Usage anywhere in your app
391export { logger }
392β
393// Example usage
394const fetchUserData = createServerFn().handler(async ({ data: userId }) => {
395 logger('info', 'Fetching user data', { userId })
396β
397 try {
398 const user = await db.users.findUnique({ where: { id: userId } })
399 logger('info', 'User data fetched successfully', { userId })
400 return user
401 } catch (error) {
402 logger('error', 'Failed to fetch user data', {
403 userId,
404 error: error.message,
405 })
406 throw error
407 }
408})
409```
410β
411### Simple Error Reporting
412β
413Basic error reporting without external dependencies:
414β
415```tsx
416// utils/error-reporter.ts
417const errorStore = new Map<
418 string,
419 { count: number; lastSeen: Date; error: any }
420>()
421β
422export function reportError(error: Error, context?: any) {
423 const key = `${error.name}:${error.message}`
424 const existing = errorStore.get(key)
425β
426 if (existing) {
427 existing.count++
428 existing.lastSeen = new Date()
429 } else {
430 errorStore.set(key, {
431 count: 1,
432 lastSeen: new Date(),
433 error: {
434 name: error.name,
435 message: error.message,
436 stack: error.stack,
437 context,
438 },
439 })
440 }
441β
442 // Log immediately
443 console.error('[ERROR REPORTED]:', {
444 error: error.message,
445 count: existing ? existing.count : 1,
446 context,
447 })
448}
449β
450// Error reporting endpoint
451// routes/errors.ts
452export const Route = createFileRoute('/admin/errors')({
453 server: {
454 handlers: {
455 GET: async () => {
456 const errors = Array.from(errorStore.entries()).map(([key, data]) => ({
457 id: key,
458 ...data,
459 }))
460β
461 return Response.json({ errors })
462 },
463 },
464 },
465})
466```
467β
468## External Observability Tools
469β
470While TanStack Start provides built-in observability patterns, external tools offer more comprehensive monitoring:
471β
472### Other Popular Tools
473β
474**Application Performance Monitoring:**
475β
476- **[DataDog](https://www.datadoghq.com/)** - Full-stack monitoring with APM
477- **[New Relic](https://newrelic.com/)** - Performance monitoring and alerting
478- **[Honeycomb](https://honeycomb.io/)** - Observability for complex systems
479β
480**Error Tracking:**
481β
482- **[Bugsnag](https://bugsnag.com/)** - Error monitoring with deployment tracking
483- **[Rollbar](https://rollbar.com/)** - Real-time error alerting
484β
485**Analytics & User Behavior:**
486β
487- **[PostHog](https://posthog.com/)** - Product analytics with error tracking
488- **[Mixpanel](https://mixpanel.com/)** - Event tracking and user analytics
489β
490### New Relic Integration
491β
492[New Relic](https://newrelic.com/) is a popular application performance monitoring tool. Here's how to integrate it with TanStack Start.
493β
494#### SSR
495β
496To enable New Relic for server-side rendering, you will need to do the following:
497β
498Create a new integration on New Relic of type `Node`. You will be given a license key that we will use below.
499β
500```js
501// newrelic.js - New Relic agent configuration
502exports.config = {
503 app_name: ['YourTanStackApp'], // Your application name in New Relic
504 license_key: 'YOUR_NEW_RELIC_LICENSE_KEY', // Your New Relic license key
505 agent_enabled: true,
506 distributed_tracing: { enabled: true },
507 span_events: { enabled: true },
508 transaction_events: { enabled: true },
509 // Additional default settings
510}
511```
512β
513```tsx
514// server.tsx
515import newrelic from 'newrelic' // Make sure this is the first import
516import {
517 createStartHandler,
518 defaultStreamHandler,
519 defineHandlerCallback,
520} from '@tanstack/react-start/server'
521import type { ServerEntry } from '@tanstack/react-start/server-entry'
522β
523const customHandler = defineHandlerCallback(async (ctx) => {
524 // We do this so that transactions are grouped under the route ID instead of unique URLs
525 const matches = ctx.router?.state?.matches ?? []
526 const leaf = matches[matches.length - 1]
527 const routeId = leaf?.routeId ?? new URL(ctx.request.url).pathname
528β
529 newrelic.setControllerName(routeId, ctx.request.method ?? 'GET')
530 newrelic.addCustomAttributes({
531 'route.id': routeId,
532 'http.method': ctx.request.method,
533 'http.path': new URL(ctx.request.url).pathname,
534 // Any other custom attributes you want to add
535 })
536β
537 return defaultStreamHandler(ctx)
538})
539β
540export default {
541 fetch(request) {
542 const handler = createStartHandler(customHandler)
543 return handler(request)
544 },
545} satisfies ServerEntry
546```
547β
548```bash
549node -r newrelic .output/server/index.mjs
550```
551β
552#### Server Functions and Server Routes
553β
554If you want to add monitoring for server functions and server routes, you will need to follow the steps above, and then add the following:
555β
556```ts
557// newrelic-middleware.ts
558import newrelic from 'newrelic'
559import { createMiddleware } from '@tanstack/react-start'
560β
561export const nrTransactionMiddleware = createMiddleware().server(
562 async ({ request, next }) => {
563 const reqPath = new URL(request.url).pathname
564 newrelic.setControllerName(reqPath, request.method ?? 'GET')
565 return await next()
566 },
567)
568```
569β
570```ts
571// start.ts
572import { createStart } from '@tanstack/react-start'
573import { nrTransactionMiddleware } from './newrelic-middleware'
574β
575export const startInstance = createStart(() => {
576 return {
577 requestMiddleware: [nrTransactionMiddleware],
578 }
579})
580```
581β
582#### SPA & Browser
583β
584Create a new integration on New Relic of type `React`.
585β
586After you set it up, you will have to add the integration script that New Relic provides you with to your root route.
587β
588```tsx
589// __root.tsx
590export const Route = createRootRoute({
591 head: () => ({
592 scripts: [
593 {
594 id: 'new-relic',
595β
596 // either copy/paste your New Relic integration script here
597 children: `...`,
598β
599 // or you can create it in your public folder and then reference it here
600 src: '/newrelic.js',
601 },
602 ],
603 }),
604})
605```
606β
607### OpenTelemetry Integration (Experimental)
608β
609[OpenTelemetry](https://opentelemetry.io/) is the industry standard for observability. Here's an experimental approach to integrate it with TanStack Start:
610β
611```tsx
612// instrumentation.ts - Initialize before your app
613import { NodeSDK } from '@opentelemetry/sdk-node'
614import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
615import { Resource } from '@opentelemetry/resources'
616import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
617β
618const sdk = new NodeSDK({
619 resource: new Resource({
620 [SemanticResourceAttributes.SERVICE_NAME]: 'tanstack-start-app',
621 [SemanticResourceAttributes.SERVICE_VERSION]: '1.0.0',
622 }),
623 instrumentations: [getNodeAutoInstrumentations()],
624})
625β
626// Initialize BEFORE importing your app
627sdk.start()
628```
629β
630```tsx
631// Server function tracing
632import { trace, SpanStatusCode } from '@opentelemetry/api'
633β
634const tracer = trace.getTracer('tanstack-start')
635β
636const getUserWithTracing = createServerFn({ method: 'GET' })
637 .validator((id: string) => id)
638 .handler(async ({ data: id }) => {
639 return tracer.startActiveSpan('get-user', async (span) => {
640 span.setAttributes({
641 'user.id': id,
642 operation: 'database.query',
643 })
644β
645 try {
646 const user = await db.users.findUnique({ where: { id } })
647 span.setStatus({ code: SpanStatusCode.OK })
648 return user
649 } catch (error) {
650 span.recordException(error)
651 span.setStatus({
652 code: SpanStatusCode.ERROR,
653 message: error.message,
654 })
655 throw error
656 } finally {
657 span.end()
658 }
659 })
660 })
661```
662β
663```tsx
664// Middleware for automatic tracing
665import { createMiddleware } from '@tanstack/react-start'
666import { trace, SpanStatusCode } from '@opentelemetry/api'
667β
668const tracer = trace.getTracer('tanstack-start')
669β
670const tracingMiddleware = createMiddleware().server(
671 async ({ next, request }) => {
672 const url = new URL(request.url)
673β
674 return tracer.startActiveSpan(
675 `${request.method} ${url.pathname}`,
676 async (span) => {
677 span.setAttributes({
678 'http.method': request.method,
679 'http.url': request.url,
680 'http.route': url.pathname,
681 })
682β
683 try {
684 const result = await next()
685 span.setAttribute('http.status_code', result.response.status)
686 span.setStatus({ code: SpanStatusCode.OK })
687 return result
688 } catch (error) {
689 span.recordException(error)
690 span.setStatus({
691 code: SpanStatusCode.ERROR,
692 message: error.message,
693 })
694 throw error
695 } finally {
696 span.end()
697 }
698 },
699 )
700 },
701)
702```
703β
704> **Note**: The above OpenTelemetry integration is experimental and requires manual setup. We're exploring first-class OpenTelemetry support that would provide automatic instrumentation for server functions, middleware, and route loaders.
705β
706### Quick Integration Pattern
707β
708Most observability tools follow a similar integration pattern with TanStack Start:
709β
710```tsx
711// Initialize in app entry point
712import { initObservabilityTool } from 'your-tool'
713β
714initObservabilityTool({
715 dsn: import.meta.env.VITE_TOOL_DSN,
716 environment: import.meta.env.NODE_ENV,
717})
718β
719// Server function middleware
720const observabilityMiddleware = createMiddleware().handler(async ({ next }) => {
721 return yourTool.withTracing('server-function', async () => {
722 try {
723 return await next()
724 } catch (error) {
725 yourTool.captureException(error)
726 throw error
727 }
728 })
729})
730```
731β
732## Best Practices
733β
734### Development vs Production
735β
736```tsx
737// Different strategies per environment
738const observabilityConfig = {
739 development: {
740 logLevel: 'debug',
741 enableTracing: true,
742 enableMetrics: false, // Too noisy in dev
743 },
744 production: {
745 logLevel: 'warn',
746 enableTracing: true,
747 enableMetrics: true,
748 enableAlerting: true,
749 },
750}
751```
752β
753### Performance Monitoring Checklist
754β
755- [ ] **Server Function Performance**: Track execution times
756- [ ] **Route Loading Times**: Monitor loader performance
757- [ ] **Database Query Performance**: Log slow queries
758- [ ] **External API Latency**: Monitor third-party service calls
759- [ ] **Memory Usage**: Track memory consumption patterns
760- [ ] **Error Rates**: Monitor error frequency and types
761β
762### Security Considerations
763β
764- Never log sensitive data (passwords, tokens, PII)
765- Use structured logging for better parsing
766- Implement log rotation in production
767- Consider compliance requirements (GDPR, CCPA)
768β
769## Future OpenTelemetry Support
770β
771Direct OpenTelemetry support is coming to TanStack Start, which will provide automatic instrumentation for server functions, middleware, and route loaders without the manual setup shown above.
772β
773## Resources
774β
775- **[Sentry Documentation](https://docs.sentry.io/)**
776- **[OpenTelemetry Documentation](https://opentelemetry.io/docs/)** - Industry standard observability
777- **[Working Example](https://github.com/TanStack/router/tree/main/examples/react/start-basic)** - See observability patterns in action