Skip to Content
Senri

WebSocket

Write WebSocket routes with upgradeWebSocket() from @senrijs/senri/websocket

import {  } from "@senrijs/senri";
import {  } from "@senrijs/senri/websocket";

const  = ();

.(
    "/chat",
    (() => ({
        () {
            .(`hello ${.("name")}`);
        },
        (, ) {
            .();       // data: string for text, Uint8Array for binary
        },
        (, , ) {},
        (, ) {},   // also receives what the other handlers throw
    })),
);

Routes are written the same way on every runtime.

What each runtime needs

RuntimeNeedsLimit of one message
BunNothing with serve(). When you call Bun.serve yourself, pass websocket (Bun)16 MiB (Bun's default)
DenoNothingDeno's default
Node.jsInstall the ws package and pass it to serve() (below)maxPayload of ws (the default is 100 MiB, so always set it)
Cloudflare WorkersNothing1 MiB (the Workers limit)
Browser (Service Worker)Not available (501)
Node.js
import {  } from "ws";
import {  } from "@senrijs/senri/serve";   // serve() from @senrijs/senri/node works the same

await (, { : new ({ : true, : 1024 * 1024 }) });

On Node.js, Senri does not parse WebSocket frames itself: it leaves them to the proven ws (Senri gets no new dependencies).

  • Without webSocketServer, WebSocket routes return 500 (development mode shows how to pass it)
  • In development mode, a notice is printed on start if the maxPayload of the WebSocketServer you passed is still the ws default (100 MiB)

What it protects

  • Connections from pages on other sites are rejected with 403 by default (against Cross-Site WebSocket Hijacking). Only connections whose Origin host matches Host pass. Add other origins with upgradeWebSocket(create, { origin: ["https://app.example.com"] }). Connections without Origin (not from a browser) pass
  • Middleware runs the same as for normal requests. If authentication middleware returns 401, there is no upgrade
  • Requests without Upgrade: websocket get 426

Negotiating subprotocols (Sec-WebSocket-Protocol) and configuring compression (permessage-deflate) are not supported yet.

Options

Prop

Type

On this page