Skip to content

Latest commit

 

History

History
263 lines (213 loc) · 10.2 KB

tanstack-start.md

File metadata and controls

263 lines (213 loc) · 10.2 KB

Integrate TanStack Start with StatLite Metrics

Use this recipe to monitor a TanStack Start React application through the StatLite Metrics v1 profile. It uses a custom Start server entry, Node.js built-ins, and the existing statlite-metrics target. The instrumentation requires no additional metrics dependency. The runnable demo includes the two source files below and a StatLite configuration.

When to use this integration

Use this recipe for a single persistent Node.js process running a production Nitro node-server build. The verified Linux x86-64 baseline uses Node.js 24.23.0, React Start 1.170.0, React Router 1.170.46, React and React DOM 19.3.1, Vite 8.4.1, and Nitro 3.0.261103-rc.

Add the helper and server entry

In an existing React Start app, save the metrics helper as src/statlite-metrics.ts:

const startedAt = new Date(Date.now() - process.uptime() * 1000).toISOString()
const totals = {
  requests_total: 0,
  responses_404_total: 0,
  responses_4xx_total: 0,
  responses_5xx_total: 0,
  request_duration_seconds_total: 0,
}

let lastCpu = process.cpuUsage()
let lastTime = process.hrtime.bigint()
let cpuCores: number | undefined

export function record(status: number, seconds: number) {
  totals.requests_total++
  if (status === 404) totals.responses_404_total++
  if (status >= 400 && status < 500) totals.responses_4xx_total++
  if (status >= 500 && status < 600) totals.responses_5xx_total++
  totals.request_duration_seconds_total += seconds
}

export function snapshot() {
  const now = process.hrtime.bigint()
  const elapsedMicros = Number(now - lastTime) / 1_000
  if (elapsedMicros >= 1_000_000) {
    const cpu = process.cpuUsage()
    cpuCores = (cpu.user + cpu.system - lastCpu.user - lastCpu.system) / elapsedMicros
    lastCpu = cpu
    lastTime = now
  }

  return Response.json({
    schema: 'statlite-metrics/v1',
    integration: 'tanstack-start',
    status: 'UP',
    started_at: startedAt,
    metrics: {
      ...totals,
      ...(cpuCores === undefined ? {} : { process_cpu_usage: cpuCores }),
      runtime_heap_used_bytes: process.memoryUsage().heapUsed,
      uptime_seconds: process.uptime(),
    },
  }, { headers: { 'Cache-Control': 'no-store' } })
}

Save the server entry as src/server.ts. Start discovers that path by default. If you already have a custom entry, wrap its existing fetch handler and forward its request options. Keep existing middleware and CSRF configuration in src/start.ts.

import start, { createServerEntry } from '@tanstack/react-start/server-entry'
import { record, snapshot } from './statlite-metrics'

export default createServerEntry({
  async fetch(request, options) {
    if (new URL(request.url).pathname === '/statlite/metrics') {
      if (request.method !== 'GET') {
        return new Response(null, { status: 405, headers: { Allow: 'GET' } })
      }
      return snapshot()
    }

    const started = performance.now()
    const response = await start.fetch(request, options)
    record(response.status, (performance.now() - started) / 1000)
    return response
  },
})

The tested Vite configuration uses the Nitro Node server preset. Apply the preset in your existing Vite config:

import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import react from '@vitejs/plugin-react'
import { nitro } from 'nitro/vite'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [tanstackStart(), nitro({ preset: 'node-server' }), react()],
})

Endpoint behavior

GET /statlite/metrics returns a fresh JSON snapshot with Cache-Control: no-store. The entry handles the reserved path before starting the timer or calling Start. Query strings do not change the match. Other methods on that path receive a 405 and are also excluded from the counters.

The wrapper counts the response returned by Start after error handling. This includes unmatched URLs that reach Start and return 404, and ordinary server-route exceptions that Start converts to 500. Each 404 also increments the 4xx counter. Snapshot collection reads local counters and Node.js process values without database or network I/O.

Required and optional fields

The response includes the required schema and status. The optional integration: "tanstack-start" identifies this producer. The example's UP means the application is serving the metrics snapshot. Add database_status only when you have an authoritative, inexpensive or cached health signal.

The helper reports cumulative requests, errors, and duration in seconds. It samples user plus system process CPU over monotonic intervals of at least one second and reports CPU cores. CPU is omitted until the first interval is available. Heap is current V8 heap use in bytes. started_at and uptime_seconds identify the process and help StatLite detect restarts.

Configure StatLite

Save this as statlite.yaml:

server:
  listen: "127.0.0.1:9090"

storage:
  sqlite_path: "./statlite.sqlite"

polling:
  interval: "30s"

targets:
  - name: "tanstack-start"
    type: "statlite-metrics"
    url: "http://127.0.0.1:3000/statlite/metrics"

Run and verify

Build the instrumented app with a build script that runs vite build, then start the production server:

npm run build
NODE_ENV=production HOST=127.0.0.1 PORT=3000 node .output/server/index.mjs

From another terminal, inspect the endpoint and start StatLite:

curl -fsS http://127.0.0.1:3000/statlite/metrics
statlite inspect http://127.0.0.1:3000
statlite --config ./statlite.yaml

Expect inspection to identify statlite-metrics. Inspection probes additional application paths, so compare traffic counters after inspection finishes. Open http://127.0.0.1:9090 and wait for the first poll. Request a working page and an unmatched URL, then compare snapshots before and after. In a test app, also exercise a server route that throws an ordinary exception and returns 500 through Start's error handler.

curl -sS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:3000/
curl -sS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:3000/does-not-exist
curl -fsS 'http://127.0.0.1:3000/statlite/metrics?check=1'

The unmatched request increments both 404 and 4xx by one. A thrown exception returned as a 500 increments 5xx by one. Polling and direct scrapes leave all HTTP counters and cumulative duration unchanged.

Reading the dashboard

StatLite dashboard showing TanStack Start requests, HTTP errors, average latency, process CPU and V8 heap

  • Status cards show reported application status, process start time, detected restarts, and scrape health. The demo leaves database health unreported.
  • Requests and HTTP errors show response counts between polls. The 404 series is included in 4xx. Request and 5xx deltas feed Attention's elevated 5xx check when its configured thresholds and poll coverage are met.
  • Average latency divides the change in cumulative duration by the number of requests in the interval. Timing ends when Start returns the response. An interval without requests has no latency value.
  • Process runtime shows V8 heap use and process CPU in cores. A CPU reading of 0.10 cores represents 10% of one logical CPU over the sampling interval.

See the dashboard guide for time ranges and counter deltas.

Instrumentation overhead

The recipe uses Node.js built-ins and five cumulative request counters. It adds no runtime dependencies, and the counters occupy fixed space regardless of how many routes the application serves.

Measurement Uninstrumented Metrics v1
Median idle RSS across trials 71.0–72.1 MiB 71.8–72.1 MiB
Median loaded RSS across trials 76.0–78.4 MiB 75.9–76.5 MiB
Process CPU per 320 requests 0.40–0.42 s 0.44 s
Short throughput run 867–899 requests/s 734–910 requests/s

The deployed build grew by 1,641 bytes excluding source maps. Metrics responses were 376–378 bytes, and trial median loopback scrape times were 0.41–0.51 ms. Throughput varied across the short trials.

The comparison used three trials per production build on a single-vCPU, 512 MiB Linux VM with no swap. The memory and CPU figures used a paced 320-request workload over four seconds at concurrency four, split between the SSR page and a server route. Throughput came from a separate 400-request run with four concurrent clients. Scrapes were timed separately.

Deployment limits

  • Coverage is limited to requests reaching the Start entry. Nitro can serve static assets outside it. Errors generated by Nitro or a proxy outside the entry are outside the measured scope.
  • Timing ends when Start returns a response. Streaming body delivery, socket completion, and failures after the response returns are outside this window. Server-function RPC error semantics were outside verification.
  • Counters and CPU sampling are process-local. Keep StatLite pointed at one stable process. Polling a load-balanced endpoint can produce misleading deltas or apparent restarts. Other adapters, edge and serverless runtimes, and multiple workers were outside verification.
  • Restrict the scrape path to loopback, a private network, or proxy access controls. The entry serves it before application middleware runs, and StatLite sends no target credentials. Make sure any proxy prefix is rewritten to /statlite/metrics and bypass cache for that path.
  • The helper reports no host CPU, memory, or disk metrics. On a collocated deployment, the StatLite self target can report those separately.

References