WebSockets@rhythmjs/ws
API reference
Every export of @rhythmjs/ws: RhythmWs, createWebsocket, websocket, and the types around them.
On this page
class RhythmWs#
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.
optionsare the pipeline options (namelabels failure messages;typedefaults to"ws") plusorigin. 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 lateruse()calls and every route. ws(path, handlers)#- Registers a
GETupgrade endpoint and returns the instance.pathis a full rou3 pattern and must start with/(otherwiseTypeError); a static segment beats a param segment.handlersmust be an object (otherwiseTypeError).Datadefaults to the route params and is inferred fromupgrade's return value.
interface WsRoute<Ctx, Data>#
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 aTypeError). Returning nothing uses the route params. Writing a response (error(ctx, 403)) or throwing refuses the handshake. headers#- Headers for the
101response, static or computed per request (async allowed): subprotocols, cookies. Runs afterupgrade; a response written there refuses the handshake. open, message, drain, close, ping, pong#- Bun's
WebSocketHandlermembers with Bun's signatures.wsis Bun'sServerWebSocket<Data>:send,subscribe,unsubscribe,publish,isSubscribed,cork,close,terminate, anddata.
createWebsocket and websocket#
function createWebsocket(behavior?: WsBehavior): Bun.WebSocketHandler<never>;
const websocket: Bun.WebSocketHandler<never>; // createWebsocket()createWebsocket(behavior?)#- Returns the single behavior object
Bun.serveaccepts aswebsocket. It spreadsbehaviorinto Bun's options verbatim and dispatchesopen,message,drain,close,ping, andpongto the route handlers carried by each connection'sws.data. One object serves everyRhythmWs. websocket#createWebsocket()with Bun's defaults, ready to pass aswebsocket.
WsBehavior and RhythmWsOptions#
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). PasstoFetchHandler(app)asfetch. 500 Upgrade failed#- Bun refused
server.upgrade(); the request answers500and the connection's registration is dropped. mounted router failed#- Errors thrown inside a mounted
RhythmWsare wrapped bymount()with the original as.cause.