rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Fixed-window rate limits#

@rhythmjs/security/rate-limit counts requests per key in a fixed window: limit requests (default 100) per windowMs (default 60 000). Within the window each request increments the key's counter; once the counter passes the limit, the middleware answers 429 with a Retry-After header holding the seconds until the window resets and a JSON body (application/json; charset=utf-8) of { success: false, status: 429, message } (message defaults to "Too Many Requests"). A skip(request) predicate exempts requests (health probes, allowlisted callers) before any counting happens.

TypeScript
import { rateLimit } from "@rhythmjs/security/rate-limit";

new RhythmRouter()
  .use(
    rateLimit({
      limit: 100,
      windowMs: 60_000,
      trustProxy: 1,
      skip: (request) => new URL(request.url).pathname === "/health/live",
    }),
  )
  .get("/api", handler);

Put it on the router (or on a route) like any request-gating middleware. It needs to know who the client is, which is the next section.

RateLimit-* headers#

Unless headers: false, every response, allowed or rejected, carries the draft-standard trio: RateLimit-Limit, RateLimit-Remaining (never negative), and RateLimit-Reset (seconds until the current window ends). Clients can pace themselves before ever hitting a 429. Skipped requests get none of them.

Choosing keys#

The default key is the client IP, resolved in this order:

  1. With trustProxy, the X-Forwarded-For entry that many hops from the right: the one your own proxy appended, so client-supplied prefixes never reach the key. The entry must be a valid IPv4 or IPv6 address, otherwise this step is skipped.
  2. Otherwise request.ip, when it is a non-empty string.
  3. Otherwise the middleware throws (rateLimit: cannot identify the client) instead of quietly putting every client in one bucket. If a single site-wide budget is what you want, say so with keyOf: () => "global".

Nothing in Rhythm or Bun sets request.ip, and the limiter only sees the Request (it does not read ctx.server). So you must do one of three things: set trustProxy behind a proxy, pass your own keyOf, or assign request.ip yourself in the fetch you give Bun.serve:

TypeScript
const handler = toFetchHandler(app);

Bun.serve({
  fetch(request, server) {
    Object.assign(request, { ip: server.requestIP(request)?.address });
    return handler(request, server);
  },
});

X-Forwarded-For is ignored unless you set trustProxy: anyone can send that header, and a limiter keyed on it hands every client an unlimited supply of fresh buckets. trustProxy takes true (one hop) or the number of proxy hops you operate. Without it, behind a proxy, every client shares the proxy's address and a single abuser exhausts the budget for everyone. With trustProxy set, a request without a usable X-Forwarded-For falls through to request.ip, and then to the error.

TypeScript
rateLimit({ trustProxy: true }); // one trusted hop (nginx, a load balancer)
rateLimit({ keyOf: async (request) => (await sessionOf(request))?.userId ?? "anonymous" });

An authenticated user id through keyOf gives fairer buckets than an IP. In tests the test client does not set request.ip either, so give rateLimit a keyOf.

Stores#

Counting goes through the RateLimitStore interface: increment(key, windowMs) returning { count, resetAt } and reset(key), each sync or async, so the backend is pluggable. The default memoryRateLimitStore() keeps counters in a Map, sweeps expired entries at most once per window, and caps the number of keys (maxKeys, default 10 000, evicting the oldest-inserted key) so a flood of distinct keys cannot grow memory without bound. It is per middleware and per process, which is exactly right for one instance and an undercount across replicas; share one instance across middleware to share a budget. For limits shared across processes, implement the two methods over a shared store (Bun's native Bun.redis client and an INCR/PEXPIRE pair fit in a dozen lines) and pass it as store.

WebSocket upgrades#

A WebSocket handshake is an ordinary HTTP request, and a RhythmWs runs its use() middleware for it, so the regular rateLimit guards upgrades as is: once the budget is spent it writes the 429, and the upgrade is never attempted.

TypeScript
import { RhythmWs } from "@rhythmjs/ws";
import { rateLimit } from "@rhythmjs/security/rate-limit";

const chat = new RhythmWs()
  .use(rateLimit({ limit: 10, windowMs: 60_000, trustProxy: 1 }))
  .ws("/ws", { message: (ws, message) => ws.send(String(message)) });

rateLimitWs(options?) also exists. It takes the same options but is a standalone middleware over a minimal { request, response: Response | undefined } context: it calls next() while the budget lasts and sets a full 429 Response (bare application/json content type, with Retry-After, plus the RateLimit-* headers unless headers: false) on ctx.response once it is spent. It is not wired to the current RhythmWs, whose context carries a mutable ctx.response object rather than a Response; reach for it only in your own upgrade code.

Secure headers#

@rhythmjs/security/secure-headers applies helmet-style response headers after your handlers run, so nothing downstream can lose them. It overwrites any same-named header a handler set, and belongs on the app, in front of mount(router), so it covers every response. Ten headers are on by default; contentSecurityPolicy and crossOriginEmbedderPolicy ship off and are set only when you configure them. Every option takes a string to override the value or false to drop the header entirely.

cross-origin-opener-policy#
same-origin
cross-origin-resource-policy#
same-origin
referrer-policy#
no-referrer
strict-transport-security#
max-age=15552000; includeSubDomains
x-content-type-options#
nosniff
x-dns-prefetch-control#
off
x-download-options#
noopen
x-frame-options#
SAMEORIGIN
x-permitted-cross-domain-policies#
none
x-xss-protection#
0 (the legacy auditor, explicitly disabled)
TypeScript
import { Rhythm, mount } from "@rhythmjs/rhythm";
import type { RhythmHttpContext } from "@rhythmjs/router/context";
import { secureHeaders } from "@rhythmjs/security/secure-headers";

const app = new Rhythm<{}, RhythmHttpContext>()
  .use(
    secureHeaders({
      contentSecurityPolicy: "default-src 'self'",
      xFrameOptions: "DENY",
      strictTransportSecurity: false, // dropped, e.g. behind a TLS-terminating proxy that sets it
    }),
  )
  .use(mount(router));