rhythmjs

Search documentation

Search guides, the tutorial and every package.

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.

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

A 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:

TypeScript
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:

TypeScript
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:

  1. A request that is not a GET with Upgrade: 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.
  2. The origin check runs. A refused origin answers 403.
  3. 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 calling next().
  4. The route's upgrade(ctx) hook runs and returns ws.data. It can also reject, by writing a response or throwing.
  5. The route's headers resolve, then ctx.server.upgrade(request, { data, headers }) is called and the response status becomes 101. If Bun refuses, the request answers 500 Upgrade failed.

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.