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
| Runtime | Needs | Limit of one message |
|---|---|---|
| Bun | Nothing with serve(). When you call Bun.serve yourself, pass websocket (Bun) | 16 MiB (Bun's default) |
| Deno | Nothing | Deno's default |
| Node.js | Install the ws package and pass it to serve() (below) | maxPayload of ws (the default is 100 MiB, so always set it) |
| Cloudflare Workers | Nothing | 1 MiB (the Workers limit) |
| Browser (Service Worker) | Not available (501) |
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
maxPayloadof theWebSocketServeryou passed is still thewsdefault (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
Originhost matchesHostpass. Add other origins withupgradeWebSocket(create, { origin: ["https://app.example.com"] }). Connections withoutOrigin(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: websocketget 426
Negotiating subprotocols (Sec-WebSocket-Protocol) and configuring compression (permessage-deflate) are not supported yet.
Options
Prop
Type