Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

observability.md

660 lines17.6 KB

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>
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 }
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 )
240​
241export function App() {
242 return (
243 <ErrorBoundary FallbackComponent={ErrorFallback}>
244 <Router />
245 </ErrorBoundary>
246 )
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 }
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 })
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 },
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 },
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