rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

class RhythmWs#

TypeScript
import { RhythmWs } from "@rhythmjs/ws";

class RhythmWs<I extends object = {}, D extends object = {}> extends Pipeline<UseContext<I & D>> {
  constructor(options?: RhythmWsOptions);

  use(middleware: Middleware | ExtensionMiddleware): this | RhythmWs<I, D & U>;
  ws<P extends string, Data extends object = InferRouteParams<P>>(path: P, route: WsRoute<RouteContext<I & D, P>, Data>): this;
}

RhythmWs is a Pipeline from @rhythmjs/rhythm, mounted into a host with mount(ws). I is the extra input the instance requires and D what its middleware derived; both are inferred.

new RhythmWs(options?)#
Creates an instance. options are the pipeline options (name labels failure messages; type defaults to "ws") plus origin.
use(middleware)#
Adds middleware over the HTTP context, the router's convention (ctx, next). It runs only for upgrade requests that match one of the instance's routes, in registration order, after the origin check and before the route. Extension middleware (derive, session, ...) widens the context for later use() calls and every route.
ws(path, handlers)#
Registers a GET upgrade endpoint and returns the instance. path is a full rou3 pattern and must start with / (otherwise TypeError); a static segment beats a param segment. handlers must be an object (otherwise TypeError). Data defaults to the route params and is inferred from upgrade's return value.

interface WsRoute<Ctx, Data>#

TypeScript
interface WsRoute<Ctx extends object, Data extends object> {
  upgrade?(ctx: Ctx): Data | void | Promise<Data | void>;
  headers?: Bun.HeadersInit | ((ctx: Ctx) => Bun.HeadersInit | Promise<Bun.HeadersInit>);
  open?(ws: Bun.ServerWebSocket<Data>): void | Promise<void>;
  message?(ws: Bun.ServerWebSocket<Data>, message: string | Buffer): void | Promise<void>;
  drain?(ws: Bun.ServerWebSocket<Data>): void | Promise<void>;
  close?(ws: Bun.ServerWebSocket<Data>, code: number, reason: string): void | Promise<void>;
  ping?(ws: Bun.ServerWebSocket<Data>, data: Buffer): void | Promise<void>;
  pong?(ws: Bun.ServerWebSocket<Data>, data: Buffer): void | Promise<void>;
}

Ctx is the request context for the path: request, params, server, response, and everything derived by earlier middleware.

upgrade(ctx)#
Runs once per handshake, before the socket exists. Returns this connection's ws.data: a fresh object every time (a shared object throws a TypeError). Returning nothing uses the route params. Writing a response (error(ctx, 403)) or throwing refuses the handshake.
headers#
Headers for the 101 response, static or computed per request (async allowed): subprotocols, cookies. Runs after upgrade; a response written there refuses the handshake.
open, message, drain, close, ping, pong#
Bun's WebSocketHandler members with Bun's signatures. ws is Bun's ServerWebSocket<Data>: send, subscribe, unsubscribe, publish, isSubscribed, cork, close, terminate, and data.

createWebsocket and websocket#

TypeScript
function createWebsocket(behavior?: WsBehavior): Bun.WebSocketHandler<never>;
const websocket: Bun.WebSocketHandler<never>; // createWebsocket()
createWebsocket(behavior?)#
Returns the single behavior object Bun.serve accepts as websocket. It spreads behavior into Bun's options verbatim and dispatches open, message, drain, close, ping, and pong to the route handlers carried by each connection's ws.data. One object serves every RhythmWs.
websocket#
createWebsocket() with Bun's defaults, ready to pass as websocket.

WsBehavior and RhythmWsOptions#

TypeScript
interface WsBehavior {
  maxPayloadLength?: number;
  idleTimeout?: number;
  backpressureLimit?: number;
  closeOnBackpressureLimit?: boolean;
  sendPings?: boolean;
  publishToSelf?: boolean;
  perMessageDeflate?: Bun.WebSocketHandler<never>["perMessageDeflate"];
}

type WsOrigin =
  | "same-origin"
  | readonly string[]
  | ((origin: string, request: Request) => boolean | Promise<boolean>)
  | false;

interface RhythmWsOptions extends PipelineOptions {
  origin?: WsOrigin;
}

WsBehavior is Bun's websocket tuning; see Serving & tuning. origin validates the handshake's Origin header before middleware runs. The default "same-origin" requires a present Origin to have the same host as the request's Host and answers 403 otherwise; requests without an Origin pass. An array allows exactly those origins, a predicate decides per request, and false disables the check.

Errors#

ctx.server is undefined#
Thrown when a matching upgrade runs without Bun's server, i.e. the app was called without fetch(request, server). Pass toFetchHandler(app) as fetch.
500 Upgrade failed#
Bun refused server.upgrade(); the request answers 500 and the connection's registration is dropped.
TypeError: new data object#
upgrade returned an object that already belongs to another connection. Return a fresh object per connection.
mounted router failed#
Errors thrown inside a mounted RhythmWs are wrapped by mount() with the original as .cause.