rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Install#

@rhythmjs/observability ships four modules, each on its own subpath export; there is no root barrel. This page covers the three per-request middlewares: /log, /request-id, and /timing; the /health module has its own page. They sit at the HTTP edge: .use() them on the Rhythm app (or on a router) ahead of your routes.

Shell
bun add @rhythmjs/observability @rhythmjs/rhythm @rhythmjs/router

Log requests#

log(sink?) wraps the chain and reports one structured LogEntry per request: { method, path, status, duration }, with path the pathname without the query string and duration in whole milliseconds. The default sink prints METHOD /path status Nms to the console; pass your own sync or async LogSink to ship entries anywhere; it is awaited, so backpressure applies.

When downstream throws, the entry is logged with status: 500 and the thrown value under error, then the error is rethrown: an exception filter registered outside log still sees it, and the failure is never swallowed by observability. The logged 500 is not necessarily what the client receives if an outer layer maps the error to something else.

TypeScript
import { RhythmRouter } from "@rhythmjs/router";
import { log } from "@rhythmjs/observability/log";
import { json } from "@rhythmjs/router/response";

new RhythmRouter().use(log()).get("/users/:id", (ctx) => {
  json(ctx, { id: ctx.params.id });
});
// => GET /users/7 200 2ms

// a custom sink
log((entry) => logger.info({ ...entry, requestId: currentRequestId() }));

Correlate with request ids#

requestId(header?) reuses the incoming id header when the caller sent one (so ids survive proxy hops) or generates a crypto.randomUUID(). An incoming id is only reused when it matches ^[A-Za-z0-9._-]{1,128}$; anything else is replaced, so clients cannot inject arbitrary content into your logs. The id is set on the response header and derived onto the context as ctx.requestId (RequestIdContext). The header name defaults to x-request-id; pass another to match your infrastructure.

TypeScript
import { requestId } from "@rhythmjs/observability/request-id";
import { text } from "@rhythmjs/router/response";

new RhythmRouter().use(requestId()).get("/ping", (ctx) => {
  text(ctx, ctx.requestId); // also sent back as x-request-id
});

requestId is a derive step, so it widens the context for everything after it. When you .use() it on the app, a router that reads ctx.requestId declares what it expects from the app: new RhythmRouter<RequestIdContext>(), and mount() checks at compile time that the app provides it.

Measure with Server-Timing#

timing(name?) appends a Server-Timing header after next() with the duration of everything downstream, measured with Bun's native Bun.nanoseconds() and reported to one decimal of a millisecond, visible per request in browser devtools. The metric name defaults to app. Because the header is appended, nested layers each contribute their own metric instead of overwriting each other. If downstream throws, no header is added.

TypeScript
import { timing } from "@rhythmjs/observability/timing";
import { text } from "@rhythmjs/router/response";

new RhythmRouter()
  .use(timing()) // app;dur=3.1
  .use(timing("db")) // db;dur=2.4, everything inside, i.e. the handler and below
  .get("/ping", (ctx) => {
    text(ctx, "pong");
  });
// => server-timing: app;dur=3.1, db;dur=2.4

Compose them#

Register log outermost so it measures and reports everything including the other observability layers, then timing, then requestId, then your routers. On the app that looks like this:

TypeScript
import { Rhythm, mount } from "@rhythmjs/rhythm";
import { RhythmRouter } from "@rhythmjs/router";
import type { RhythmHttpContext } from "@rhythmjs/router/context";
import { toFetchHandler } from "@rhythmjs/router/fetch";
import { requestId, type RequestIdContext } from "@rhythmjs/observability/request-id";
import { json } from "@rhythmjs/router/response";

const users = new RhythmRouter<RequestIdContext>().get("/users/:id", (ctx) => {
  json(ctx, { id: ctx.params.id, requestId: ctx.requestId });
});

const app = new Rhythm<{}, RhythmHttpContext>()
  .use(log())
  .use(timing())
  .use(requestId())
  .use(mount(users));

Bun.serve({ fetch: toFetchHandler(app) });
// => GET /users/7 200 2ms, with x-request-id and server-timing on the response