WebSockets@rhythmjs/ws
Quick start
A pipeline you mount beside your routers: Bun does the upgrade, your handlers are Bun's own, and ws.data is typed from what you return.
On this page
Install the package#
@rhythmjs/ws adds WebSocket routes to a Rhythm app. It is built on Bun's own WebSocket model and adds only what Bun leaves to you: matching upgrade requests to endpoints, running middleware over the handshake, and deciding what each connection's ws.data is. After the upgrade, handlers are Bun's WebSocketHandler members receiving Bun's ServerWebSocket, and fan-out is Bun's native pub/sub.
RhythmWs is a Pipeline, exactly like RhythmRouter: the same use() middleware, the same rou3 :param paths, and the same mount() into a host. @rhythmjs/rhythm and @rhythmjs/router are peer dependencies (0.0.24 or newer), and Bun 1.2 or newer is required.
bun add @rhythmjs/ws @rhythmjs/rhythm @rhythmjs/routerA first route#
.ws(path, handlers) registers an endpoint. The upgrade(ctx) hook returns this connection's ws.data; the remaining members (open, message, close, ...) are Bun's, and they see that data typed:
import { RhythmWs } from "@rhythmjs/ws";
const ws = new RhythmWs().ws("/ws/rooms/:id", {
upgrade(ctx) {
return { room: ctx.params.id, handle: crypto.randomUUID().slice(0, 6) }; // becomes ws.data
},
open(peer) {
peer.subscribe(`room:${peer.data.room}`);
},
message(peer, message) {
peer.publish(`room:${peer.data.room}`, `${peer.data.handle}: ${String(message)}`);
},
close(peer) {
peer.publish(`room:${peer.data.room}`, `${peer.data.handle} left`);
},
});The examples name the socket peer; it is Bun's ServerWebSocket<Data> with send, subscribe, publish, close, and the rest. Paths are complete: there is no prefix option, and a path must start with /.
Mount it and serve it#
Mount the instance in the host app next to your routers. Serving is one Bun.serve call: toFetchHandler(app) passes Bun's server through as ctx.server, which is what performs the upgrade, and websocket is the one handler object Bun needs for every socket in the process:
import { Rhythm, mount } from "@rhythmjs/rhythm";
import { RhythmRouter } from "@rhythmjs/router";
import { toFetchHandler } from "@rhythmjs/router/fetch";
import { RhythmWs, websocket } from "@rhythmjs/ws";
import { text } from "@rhythmjs/router/response";
const http = new RhythmRouter().get("/health", (ctx) => text(ctx, "ok"));
const app = new Rhythm().use(mount(http)).use(mount(ws));
Bun.serve({
port: 3000,
fetch: toFetchHandler(app),
websocket,
});Host types are inferred: mounting a RhythmWs widens the host's input the same way mounting a router does, so no explicit generics are needed. To tune Bun's per-server options, replace websocket with createWebsocket({ idleTimeout: 120 }), covered in Serving & tuning.
What happens to a request#
For every request, the pipeline does the following, in order:
- A request that is not a
GETwithUpgrade: websocket, or whose path matches no.ws()route, passes straight through to the rest of the app. Middleware never runs for it, so a miss costs nothing and a router mounted after the instance can still answer. - The origin check runs. A refused origin answers
403. - The
use()middleware runs in registration order over the HTTP context. A middleware rejects the handshake by writing a response (error(ctx, 401)) instead of callingnext(). - The route's
upgrade(ctx)hook runs and returnsws.data. It can also reject, by writing a response or throwing. - The route's
headersresolve, thenctx.server.upgrade(request, { data, headers })is called and the response status becomes101. If Bun refuses, the request answers500 Upgrade failed.
The upgrade needs the server that Bun.serve hands to fetch(request, server). fetch: toFetchHandler(app) does that for you. Calling the handler by hand without a server throws ctx.server is undefined: call the fetch handler with Bun's server, which is also why the testing harness supplies a mock one.
Where to go next#
Routes & ws.data#- Typed connection data: params as the default,
upgrade(ctx), rejecting, handshake headers and subprotocols. Middleware & auth#- Guarding the handshake: sessions, guards, rate limits, ordering, and the origin check.
Rooms & pub/sub#- Fan-out: joining rooms by message, authorizing joins, and publishing from HTTP routes.
Serving & tuning#- Bun.serve options:
createWebsocket, backpressure, and scaling beyond one process.