qat

Field vitals

@qatjs/vitals measures how your app performs for real visitors: TTFB, LCP, CLS and INP, per route, sent to an endpoint you own. It is off until you call it.

JavaScript7 lines
// src/main.js
import { render } from '@qatjs/core'
import { vitals } from '@qatjs/vitals'
import routes from './routes.js'

vitals({ endpoint: '/vitals', router: routes })
render(routes, document.getElementById('app'))
  • Per route pattern. Entries are keyed by the route's pattern, /products/:id, never the URL. With router, vitals uses the pattern the router matched. Without a router it uses location.pathname when vitals() runs, with numeric and UUID segments written as :id (/orders/42 → /orders/:id).
  • One beacon per route visit, sent with navigator.sendBeacon. When the route pattern changes, the previous route's entry is sent. When the page is hidden (a tab switch, closing the page), the current route's entry is sent. A visit that measured nothing sends nothing. If the visitor comes back to the page, the rest of the visit becomes a new entry.
  • Your endpoint only. endpoint must be a relative path or a URL on the page's own origin. Anything else throws when vitals() runs: @qatjs/vitals: the endpoint must be same-origin: https://collector.example/vitals. There is no default endpoint. Qat never sends data to Qat.
  • Identifier-free. A beacon holds the route pattern, the metric values and the format version. There are no user or session ids, no URLs and no query strings, and vitals reads no cookies. (The browser still attaches your origin's cookies to a same-origin request, as it does to any other. Your endpoint should not read them.)
  • Call it once, early: in main.js, before or right after render. It reads metrics the browser already recorded (buffered), so the page load's TTFB and LCP are never missed.

Qat never sends data to Qat. Any endpoint is the project's own; production collection is opt-in, identifier-free, counters only. A build profile (qatjs dev --count, qatjs compress --profile) is a file of the project's: nothing reads it but its own toolchain.

What is measured

Metric Unit Value for a visit
TTFB ms responseStart of the page's navigation (first visit of a page load only)
LCP ms startTime of the last largest-contentful-paint candidate (first visit only: browsers stop reporting LCP after the first input)
CLS score the sum of the visit's layout shifts, leaving out shifts within 500 ms of input
INP ms the slowest interaction (event entries ≥ 16 ms, and the first input)

Notes on the definitions:

  • CLS is the sum over the visit. The web-vitals definition is the largest session window (shifts under 1 s apart, at most 5 s long). The two are equal when a visit's shifts fall within one window, and the sum is never lower, so a budget passed on this value is also passed on the windowed value.
  • INP is the slowest interaction of the visit. That is INP exactly for a visit with fewer than 50 interactions; the full definition ignores one outlier per 50. An interaction counts for the route that is showing when the browser reports it, which happens after the next paint.
  • Metrics a browser does not support are left out of the entry. A missing key means "not measured"; it never means 0.
  • When LCP stops and when an interaction is reported are the browser's rules (the Largest Contentful Paint and Event Timing specifications), not Qat's. examples/vitals-cases' e2e checks what Qat adds: one entry per route pattern, free of identifiers, sent to the app's own origin only.
  • Values are numbers as the browser reports them, so the milliseconds can have fractions.

Payload format (v1)

The request is a POST to endpoint. Its body is one JSON object with Content-Type: text/plain, because sendBeacon sends a string that way.

JSON1 line
{ "$schema": "https://qat.dev/schema/vitals/v1.json", "version": 1, "route": "/products/:id", "TTFB": 182.4, "LCP": 1210, "CLS": 0.02, "INP": 96 }
Key Type
$schema https://qat.dev/schema/vitals/v1.json the format, as in every Qat output (@qatjs/schemas)
version 1 the format version. A change to this table is a new version. (Beacons sent before 0.9.0-rc.2 carry v: 1 instead; readManifest(body, 'vitals') reads both.)
route string the route pattern ('*' for the router's not-found route)
TTFB, LCP, CLS, INP number, optional present when measured during the visit

There are no other keys. The TypeScript type is VitalsPayload, exported by @qatjs/vitals.

The data source for qatjs budget. qatjs budget reads these entries back from your endpoint. It computes p75 LCP, INP and CLS per route over a time window and puts them beside each route's build size and page(…, { budget }). Store each beacon as a row with the time you received it (t, ms since the epoch); that time is the only thing your endpoint adds. The p75 of a metric is over the entries that have that metric. The endpoint below answers GET with the stored rows, one per line; qatjs budget --endpoint reads that, or the file itself.

Where qatjs budget and the devtools read it: package.json#qat.vitals

JSON1 line
{ "qat": { "site": "https://shop.example/", "vitals": { "endpoint": "/vitals", "window": "28d" } } }

qatjs budget and qatjs dev --devtools (the Routes tab's p75 columns) read the rows from vitals.endpoint over vitals.window (28d by default; 12h, 2w or milliseconds). The flags --endpoint and --window win over the key. It is a project setting beside qat.site, not a config file, and it configures no code: vitals({ endpoint }) in your app is still where the beacons go.

  • A path (/vitals) is on the app's own server. qatjs budget reads it from the origin of qat.site; qatjs dev reads it from itself, so qatjs dev --proxy /vitals=http://localhost:3000 reaches the endpoint below.
  • A file (vitals.ndjson, fixtures/vitals.ndjson) is read from the project: a copy of the stored rows, or a fixture. A file that exists wins over a path of the same name.
  • A URL must be on the app's origin (qat.site's; in dev, the dev server's). Any other origin is the warning QX-VITALS-FOREIGN-ENDPOINT in qatjs check, qatjs budget and qatjs dev, and Qat does not contact it: field data is read only from the app's own server. (--endpoint <url> on the command line is read as asked, with the same warning.)

An endpoint in Node

JavaScript37 lines
// vitals-endpoint.js: node vitals-endpoint.js (or mount the handler in your server)
import { createServer } from 'node:http'
import { appendFile, readFile } from 'node:fs/promises'

const METRICS = ['TTFB', 'LCP', 'CLS', 'INP']

export async function handleVitals(req, res) {
  let body = ''
  for await (const chunk of req) if ((body += chunk).length > 2048) return res.writeHead(413).end()
  try {
    const e = JSON.parse(body)
    if ((e.version ?? e.v) !== 1 || typeof e.route !== 'string') throw new Error('not a v1 entry')
    // keep only the known keys: a row holds nothing but the route, the metrics and the time
    const row = { t: Date.now(), route: e.route.slice(0, 200) }
    for (const m of METRICS) if (Number.isFinite(e[m])) row[m] = e[m]
    await appendFile('vitals.ndjson', JSON.stringify(row) + '\n')
    res.writeHead(204).end()
  } catch {
    res.writeHead(400).end()
  }
}

// for `qatjs budget --endpoint`: the stored rows since `?since=<ms>` (protect it as you would any
// internal report)
export async function readVitals(req, res) {
  const since = Number(new URL(req.url, 'http://x').searchParams.get('since')) || 0
  const text = await readFile('vitals.ndjson', 'utf8').catch(() => '')
  const rows = text.split('\n').filter((l) => l && JSON.parse(l).t >= since)
  res.writeHead(200, { 'content-type': 'application/x-ndjson' }).end(rows.map((l) => l + '\n').join(''))
}

createServer((req, res) => {
  const path = req.url.split('?')[0]
  if (req.method === 'POST' && path === '/vitals') return handleVitals(req, res)
  if (req.method === 'GET' && path === '/vitals') return readVitals(req, res)
  res.writeHead(404).end()
}).listen(3000)

In development, qatjs dev --proxy /vitals=http://localhost:3000 sends the beacons to it, and with "vitals": { "endpoint": "/vitals" } in package.json#qat the devtools' Routes tab shows the p75s it has stored (after a qatjs compress, for the build columns).

Size

@qatjs/vitals is 0.6 kB gzip (CI-enforced in size-limit). It uses watch from @qatjs/core for the router's route and has no other dependency.