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/solid'
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/solid-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/solid-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/solid-start'
99β
100const requestLogger = createMiddleware().handler(async ({ 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 response = await next()
108 const duration = Date.now() - startTime
109β
110 console.log(
111 `[${timestamp}] ${request.method} ${request.url} - ${response.status} (${duration}ms)`,
112 )
113β
114 return response
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/solid-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 Solid.createEffect(() => {
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/solid-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 'solid-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/solid-start'
336β
337const debugMiddleware = createMiddleware().handler(async ({ next }) => {
338 const response = await next()
339β
340 if (process.env.NODE_ENV === 'development') {
341 response.headers.set('X-Debug-Timestamp', new Date().toISOString())
342 response.headers.set('X-Debug-Node-Version', process.version)
343 response.headers.set('X-Debug-Uptime', process.uptime().toString())
344 }
345β
346 return response
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/solid-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### OpenTelemetry Integration (Experimental)
491β
492[OpenTelemetry](https://opentelemetry.io/) is the industry standard for observability. Here's an experimental approach to integrate it with TanStack Start:
493β
494```tsx
495// instrumentation.ts - Initialize before your app
496import { NodeSDK } from '@opentelemetry/sdk-node'
497import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
498import { Resource } from '@opentelemetry/resources'
499import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
500β
501const sdk = new NodeSDK({
502 resource: new Resource({
503 [SemanticResourceAttributes.SERVICE_NAME]: 'tanstack-start-app',
504 [SemanticResourceAttributes.SERVICE_VERSION]: '1.0.0',
505 }),
506 instrumentations: [getNodeAutoInstrumentations()],
507})
508β
509// Initialize BEFORE importing your app
510sdk.start()
511```
512β
513```tsx
514// Server function tracing
515import { trace, SpanStatusCode } from '@opentelemetry/api'
516β
517const tracer = trace.getTracer('tanstack-start')
518β
519const getUserWithTracing = createServerFn({ method: 'GET' })
520 .validator((id: string) => id)
521 .handler(async ({ data: id }) => {
522 return tracer.startActiveSpan('get-user', async (span) => {
523 span.setAttributes({
524 'user.id': id,
525 operation: 'database.query',
526 })
527β
528 try {
529 const user = await db.users.findUnique({ where: { id } })
530 span.setStatus({ code: SpanStatusCode.OK })
531 return user
532 } catch (error) {
533 span.recordException(error)
534 span.setStatus({
535 code: SpanStatusCode.ERROR,
536 message: error.message,
537 })
538 throw error
539 } finally {
540 span.end()
541 }
542 })
543 })
544```
545β
546```tsx
547// Middleware for automatic tracing
548import { createMiddleware } from '@tanstack/solid-start'
549import { trace, SpanStatusCode } from '@opentelemetry/api'
550β
551const tracer = trace.getTracer('tanstack-start')
552β
553const tracingMiddleware = createMiddleware().handler(
554 async ({ next, request }) => {
555 const url = new URL(request.url)
556β
557 return tracer.startActiveSpan(
558 `${request.method} ${url.pathname}`,
559 async (span) => {
560 span.setAttributes({
561 'http.method': request.method,
562 'http.url': request.url,
563 'http.route': url.pathname,
564 })
565β
566 try {
567 const response = await next()
568 span.setAttribute('http.status_code', response.status)
569 span.setStatus({ code: SpanStatusCode.OK })
570 return response
571 } catch (error) {
572 span.recordException(error)
573 span.setStatus({
574 code: SpanStatusCode.ERROR,
575 message: error.message,
576 })
577 throw error
578 } finally {
579 span.end()
580 }
581 },
582 )
583 },
584)
585```
586β
587> **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.
588β
589### Quick Integration Pattern
590β
591Most observability tools follow a similar integration pattern with TanStack Start:
592β
593```tsx
594// Initialize in app entry point
595import { initObservabilityTool } from 'your-tool'
596β
597initObservabilityTool({
598 dsn: import.meta.env.VITE_TOOL_DSN,
599 environment: import.meta.env.NODE_ENV,
600})
601β
602// Server function middleware
603const observabilityMiddleware = createMiddleware().handler(async ({ next }) => {
604 return yourTool.withTracing('server-function', async () => {
605 try {
606 return await next()
607 } catch (error) {
608 yourTool.captureException(error)
609 throw error
610 }
611 })
612})
613```
614β
615## Best Practices
616β
617### Development vs Production
618β
619```tsx
620// Different strategies per environment
621const observabilityConfig = {
622 development: {
623 logLevel: 'debug',
624 enableTracing: true,
625 enableMetrics: false, // Too noisy in dev
626 },
627 production: {
628 logLevel: 'warn',
629 enableTracing: true,
630 enableMetrics: true,
631 enableAlerting: true,
632 },
633}
634```
635β
636### Performance Monitoring Checklist
637β
638- [ ] **Server Function Performance**: Track execution times
639- [ ] **Route Loading Times**: Monitor loader performance
640- [ ] **Database Query Performance**: Log slow queries
641- [ ] **External API Latency**: Monitor third-party service calls
642- [ ] **Memory Usage**: Track memory consumption patterns
643- [ ] **Error Rates**: Monitor error frequency and types
644β
645### Security Considerations
646β
647- Never log sensitive data (passwords, tokens, PII)
648- Use structured logging for better parsing
649- Implement log rotation in production
650- Consider compliance requirements (GDPR, CCPA)
651β
652## Future OpenTelemetry Support
653β
654Direct 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.
655β
656## Resources
657β
658- **[Sentry Documentation](https://docs.sentry.io/)**
659- **[OpenTelemetry Documentation](https://opentelemetry.io/docs/)** - Industry standard observability
660- **[Working Example](https://github.com/TanStack/router/tree/main/examples/solid/start-basic)** - See observability patterns in action