WebSockets@rhythmjs/ws
Middleware and auth
Upgrades run through ordinary Rhythm middleware: reuse sessions, your own guards and rate limits, and let the origin check stop cross-site hijacking.
use() over the handshake#
use(middleware) is the router's convention: (ctx, next) over the HTTP context. Middleware runs only when an upgrade request matches one of the instance's routes, in registration order, before the route's upgrade hook. Call next() to continue, or write a response to refuse the handshake:
const ws = new RhythmWs()
.use(async (ctx, next) => {
if (new URL(ctx.request.url).searchParams.get("token") === "good") await next();
else error(ctx, 401);
})
.ws("/ws/guarded", { open: (peer) => void peer.send("in") });A middleware that neither calls next() nor writes a response never reaches the upgrade, so the socket is not opened and the request falls through to the rest of the app (a plain 404 if nothing else answers). Forgetting next() can fail to authorize, never silently authorize.
derive(...) and the other extension middleware widen the context for everything after them: later use() calls and every route's upgrade and headers see the derived fields, fully typed.
Reuse what you have#
The middleware runs over the handshake request, which carries cookies and headers like any other GET, so the pieces you use on routers work on upgrades unchanged.
@rhythmjs/http#session()andcookies()from@rhythmjs/http/sessionand/cookiesare extension middleware;.use(session())andctx.sessionis available inupgradeandheaders.@rhythmjs/security#rateLimitfrom/rate-limitworks as on a router (see below). Guards you write yourself, like the ones in the tutorial, are plain(ctx, next)middleware and work the same way.@rhythmjs/better-auth#withSession()andrequireSession()apply with.use(...), on an app that providesctx.auththe way the Better Auth integration sets up.
import { session } from "@rhythmjs/http/session";
import { RhythmWs } from "@rhythmjs/ws";
import { error } from "@rhythmjs/router/response";
const ws = new RhythmWs().use(session()).ws("/ws/inbox", {
upgrade(ctx) {
const userId = ctx.session.get<string>("userId");
if (!userId) return error(ctx, 401);
return { userId };
},
open(peer) {
peer.subscribe(`user:${peer.data.userId}`);
},
});With bearer-style authentication, remember that browsers cannot set an Authorization header on new WebSocket(...): cookies (so sessions) are the natural fit, or pass a short-lived ticket in the query string and verify it in a middleware.
Do authentication at the handshake, in middleware or upgrade, not in message. Once the socket is open the handshake is over, and ws.data is the identity the connection carries for its lifetime.
Rate limiting upgrades#
Limit handshakes with rateLimit from @rhythmjs/security/rate-limit, placed before anything expensive. It answers 429 through the same context as a router would, and the request never reaches upgrade:
import { rateLimit } from "@rhythmjs/security/rate-limit";
const ws = new RhythmWs()
.use(rateLimit({ limit: 20, windowMs: 60_000, trustProxy: true }))
.ws("/ws/inbox", handlers);The limiter needs a client key. Behind a reverse proxy set trustProxy; otherwise pass keyOf, which receives only the Request; close over your Bun.serve result to use server.requestIP(request). The hardening guide covers both. Limits apply per handshake, not per message: bound message volume with maxPayloadLength and backpressure in Serving & tuning.
Order#
Middleware runs in the order you call use(), after the origin check and before the route:
- Cheap guards first: rate limit, then authentication.
- Anything
upgradereads second: derive the session or user before the route that needs it. - The route last: it only runs when every guard called
next().
Different protection levels compose as separate instances mounted into one app. Each RhythmWs runs only its own middleware, for its own routes:
const publicWs = new RhythmWs().ws("/ws/status", statusHandlers);
const memberWs = new RhythmWs().use(session()).use(requireLogin).ws("/ws/inbox", inboxHandlers);
const app = new Rhythm().use(mount(http)).use(mount(publicWs)).use(mount(memberWs));The origin check#
Browsers attach cookies to WebSocket handshakes and are exempt from CORS, so a page on another site can open a socket as your logged-in user: cross-site WebSocket hijacking. RhythmWs checks the Origin header before any middleware runs, controlled by the origin option:
new RhythmWs(); // "same-origin" (default)
new RhythmWs({ origin: ["https://app.example"] }); // exact-match allowlist
new RhythmWs({ origin: (origin, request) => origin.endsWith(".example") }); // predicate, sync or async
new RhythmWs({ origin: false }); // no check"same-origin": a request with anOriginheader must have the same host as the request's ownHostheader, or it answers403. A malformedOriginis refused too.- A request with no
Originheader (a non-browser client) always passes: the check defends cookie-carrying browsers, not authentication. Authenticate in middleware regardless. - Pass an allowlist or predicate when your frontend lives on another origin, and
falseonly when you authenticate every handshake some other way.