Server WebSocket
Esta página aún no está disponible en tu idioma.
Server-side WebSocket is part of the HTTP route DSL. The
websocket() directive upgrades matching requests and wires every
connection to a single WebsocketServerActor — the hub — which
you implement. For outbound client connections, see
WebsocketClientActor.
import { ActorSystem,} from 'actor-ts';import { HttpExtensionId, WebsocketServerActor, websocket, type WebsocketConnection,} from 'actor-ts/http';import { match } from 'ts-pattern';
type SetNameMessage = { kind: 'setName'; name: string };type SayMessage = { kind: 'say'; text: string };type ClientMessage = SetNameMessage | SayMessage;type ServerMessage = { kind: 'system'; text: string } | { kind: 'chat'; from: string; text: string };
class ChatRoom extends WebsocketServerActor<ServerMessage, ClientMessage> { private readonly names = new Map<string, string>();
onMessage(message: ClientMessage): void { match(message) .with({ kind: 'setName' }, (m) => this.onSetName(m)) .with({ kind: 'say' }, (m) => this.onSay(m)) .exhaustive(); }
private onSetName(m: SetNameMessage): void { this.names.set(this.connection.id, m.name); this.reply({ kind: 'system', text: `hi ${m.name}` }); }
private onSay(m: SayMessage): void { this.broadcast({ kind: 'chat', from: this.names.get(this.connection.id) ?? 'anon', text: m.text }); }
override onClientDisconnected(c: WebsocketConnection<ServerMessage>): void { this.names.delete(c.id); }}
const system = ActorSystem.create('chat');const chat = system.spawn(ChatRoom, 'chat');
await system.extension(HttpExtensionId) .newServerAt('0.0.0.0', 8080) .bind(websocket('/ws', chat));The hub’s type parameters read from the server’s point of
view: TOut = the messages the server sends, TIn = the decoded
messages it receives.
The websocket() directive
Section titled “The websocket() directive”websocket() produces a Route, so it composes with the rest of
the route DSL — path(), concat(), and
withMiddleware(). Two forms:
import { websocket, path, concat } from 'actor-ts/http';
// 1. Bare directive — mount it under a path yourself:path('ws', websocket(chat));
// 2. Path sugar — equivalent to path(p, websocket(target)):websocket('/ws', chat);
// Mixed with normal HTTP routes on the same server:concat( path('api', apiRoutes), websocket('/ws', chat),);Options
Section titled “Options”type WebsocketRouteOptions<TOut, TIn> = { codec?: WebsocketCodec<TOut, TIn>; // default jsonCodec() maxFrameBytes?: number; // default 1 MiB onOversizeFrame?: 'close' | 'drop'; // default 'close' (1009) onInvalidMessage?: 'close' | 'drop' | 'hook'; // default 'close' (1003) maxBufferedBytes?: number; // default 4 MiB onBackpressure?: 'drop' | 'close'; // default 'drop' allowedOrigins?: string[]; // CSWSH defence — see below requireSameOrigin?: boolean; // CSWSH defence; default true — see below maxConnections?: number; // concurrent-connection cap; default unlimited maxPreAttachFrames?: number; // setup-window frame cap; default 256 maxPreAttachBytes?: number; // setup-window byte cap; default 4 MiB acceptTimeoutMs?: number; // setup deadline; default 10 000, Infinity to disable connectionMailboxCapacity?: number; // per-connection queue bound; default unset (global bound) connectionMailboxOverflow?: 'drop-head' | 'drop-new' | 'reject'; // needs a capacity};const webSocketRouteOptions = WebsocketRouteOptions.create() .withMaxFrameBytes(256 * 1024) .withOnOversizeFrame('close') // close with 1009 Message Too Big .withOnInvalidMessage('close');websocket('/ws', chat, webSocketRouteOptions); // close with 1003 Unsupported DataThe frame-size cap is enforced on the raw frame before decode.
onInvalidMessage: 'hook' routes decode failures to the actor’s
onInvalidMessage hook instead of closing.
Where the cap is enforced
Section titled “Where the cap is enforced”maxFrameBytes is checked twice, at two different moments:
- In the transport, at your resolved
maxFrameBytes— handed to the runtime’s own socket when the server binds. A frame over it is refused while it arrives, so a hostile peer cannot make the process buffer a 16 MiB (Bun) or 100 MiB (ws) frame just to have it thrown away afterwards. Because the runtime hangs up rather than sending a policy close, the client sees an abnormal close (1006) here, not 1009. Two runtime/backend pairs have no such layer — see the caution below. - In the connection actor, at the same
maxFrameBytes— on the fully received frame, before the codec decodes it, closing with 1009.
Only the second layer is a guarantee. It runs everywhere and it is what keeps an oversize frame away from your actor; the transport cap is an optimisation on top of it that spares the process the buffering.
The number is yours in both directions: lowering maxFrameBytes narrows
the buffering window too, and raising it above the 1 MiB default really
does let frames that large through. It is resolved the usual way — route
options, then actor-ts.http.websocket.max-frame-bytes, then the built-in
default — and the resolution happens when the server binds, so a
malformed value is an error at bind() rather than on the first upgrade.
The transport cap is per server, not per route. A server has a single
transport shared by all its WebSocket routes (one WebSocketServer on
Express, one plugin registration on Fastify, one Bun.serve), so where
several routes disagree the transport takes the widest of their caps.
A stricter route is unaffected in what it accepts — the connection actor
still refuses its oversize frames with 1009 — it just does not get the
narrower buffering window it would have had on its own.
That is a decision rather than a gap. Fastify and Bun.serve can hold
only one limit at a time; Express structurally could hold one per route,
and taking it up there would make the same configuration mean different
things on different backends — for a limit whose whole job is bounding
what a hostile peer can allocate, one shape everywhere beats a narrower
window on one backend of three.
The connection setup window
Section titled “The connection setup window”Between the handshake completing and the connection’s actor attaching its listeners there is a short window — two mailbox hops — in which the socket is live and nothing is reading it. Frames that arrive there are held and replayed the moment the actor attaches, so nothing is lost. Two knobs bound what that window may cost, and both exist because the window’s exit is not guaranteed: the actor is spawned by the hub, and a hub that has stopped, stalled or been reconfigured may never produce one.
maxPreAttachFrames/maxPreAttachBytesbound what is held. Past either the socket is closed with 1013 (“try again later”) rather than buffered further. A legitimate client sends nothing or a greeting into this window, so the defaults — 256 frames, 4 MiB — are orders of magnitude above ordinary traffic; what they refuse is a peer that streams into a connection nobody has accepted yet. The first frame is always admitted whatever its size (it is already bounded bymaxFrameBytes), so a route that raisesmaxFrameBytesabove 4 MiB only needs to raisemaxPreAttachBytesif its clients send several such frames at once.acceptTimeoutMsbounds how long the window may stay open. If no connection actor has attached within it, the socket is closed with 1013 and itsmaxConnectionsslot is released. Ten seconds by default: a healthy hub attaches in microseconds, so this is a fallback, not a liveness policy — and an actor that turns up after the deadline is handed the close rather than a socket the framework already killed. SetInfinityto switch it off.
Neither is reachable by accident. Both answer the same failure: an upgraded socket with no actor behind it, which before they existed stayed open for the process lifetime, accumulated frames nothing would ever drain, and held an admission slot nothing would ever return.
A busy hub is not that failure. The command that spawns the actor is one
of the hub’s control messages, handled ahead of the frames other
connections have queued (see
Bounding the hub’s mailbox), so a backlog on
a hub with its default mailbox cannot hold a finished upgrade past
acceptTimeoutMs and turn it into a 1013. A hub spawned with
withMailbox(...) orders the command like any other message in that
mailbox, and behind a FIFO backlog that takes longer than
acceptTimeoutMs to drain the new connection is still closed with 1013.
Origin checks (CSWSH defence)
Section titled “Origin checks (CSWSH defence)”Browsers attach the user’s cookies to a WebSocket upgrade automatically, so a
WS route whose auth is ambient (a session cookie, or IpAllowlist) is open
to Cross-Site WebSocket Hijacking: any web page can open
new WebSocket('wss://your-host/ws') and ride the victim’s credentials.
Two rules gate the handshake by the browser Origin header, and they combine —
an upgrade passes when either admits it.
requireSameOrigin — on by default
Section titled “requireSameOrigin — on by default”requireSameOrigin accepts an Origin that names this same server, by
comparing it against the request’s own Host. It needs no configuration,
which is why it is the default: a route gets the check without its author
having to know the option exists.
websocket('/ws', chat); // same-origin requiredThe comparison is host-only — Host carries no scheme to compare against — so
a reverse proxy that rewrites Host but not Origin fails the check; name the
real origins in allowedOrigins instead. Host-only also means scheme-blind:
an http:// page on the same host:port passes, so this rule is not a
substitute for refusing plaintext.
Both of those headers come from the client, and that bounds what the rule can
promise. A page that reaches this server under a name of its own — DNS
rebinding — sends an Origin and a Host that agree, so it passes the
same-origin arm. This is the standard weakness of any same-origin check built
on Host, and it is why allowedOrigins exists. What it buys is
reachability rather than a session, because the browser attaches no cookies
for the real host — so the shape that matters is a route whose auth is the
network (IpAllowlist, or trusting loopback). Name the origins such a route
expects in allowedOrigins instead of leaning on this arm.
allowedOrigins — naming other origins
Section titled “allowedOrigins — naming other origins”Use it when the page driving the socket is served from somewhere else:
const wsOptions = WebsocketRouteOptions.create() .withAllowedOrigins(['https://app.example.com']);websocket('/ws', chat, wsOptions);An upgrade whose Origin is present but matches neither rule is rejected with
403 before the handshake, on all three backends. Comparison is
case-insensitive.
Missing Origin — non-browser clients are unaffected
Section titled “Missing Origin — non-browser clients are unaffected”A missing Origin is allowed, under both rules. A Node, Bun or Deno
WebSocket, and any server-to-server dialer, sends no Origin header at all,
so none of this reaches them: CSWSH rides a victim browser’s ambient
credentials, and a browser always sends the header. This is what makes the
default safe to turn on — the traffic it starts refusing is browser traffic
from a page you did not serve.
Opting out
Section titled “Opting out”const wsOptions = WebsocketRouteOptions.create() .withRequireSameOrigin(false);websocket('/ws', chat, wsOptions); // no origin check at allwithRequireSameOrigin(false) alongside withAllowedOrigins([...]) keeps the
allowlist and drops only the same-origin arm. With no allowlist it leaves the
route with no origin check whatsoever — the pre-#756 behaviour, and worth a
comment saying which credential shape makes it safe.
BearerTokenAuth is one such shape: it is already resistant, because browsers
cannot set Authorization on a WS handshake. The origin rules matter most for
cookie- or IP-based auth.
Middleware runs at upgrade time
Section titled “Middleware runs at upgrade time”withMiddleware() composes with websocket(), but the middleware
runs once, at upgrade time, against the HTTP upgrade request —
not per WebSocket message. A rejecting middleware returns a normal
HTTP error and the upgrade never completes, so auth middleware
like BearerTokenAuth or IpAllowlist gates the handshake:
import { websocket, withMiddleware } from 'actor-ts/http';
withMiddleware(BearerTokenAuth({ /* ... */ }), websocket('/ws', chat));// A bad token → HTTP 401, no upgrade. A good token → the socket opens.See the HTTP overview for the middleware set.
Response-decorating middleware works too
Section titled “Response-decorating middleware works too”A middleware that calls next() and returns a decorated copy of the
result — securityHeaders(), contentSecurityPolicy(),
strictTransportSecurity(), requestId(), csrfProtection() — composes
over a websocket() route as well, so one wrap can harden a whole tree
without carving the socket out of it:
import { requestId, securityHeaders, websocket, withMiddleware } from 'actor-ts/http';
withMiddleware(securityHeaders(), withMiddleware(requestId(), websocket('/ws', chat)));// Both run at upgrade time. The socket opens.The headers such a middleware adds do not reach a successful
handshake — the backend writes that 101 response itself, and a WebSocket
connection is not a document a browser would apply X-Frame-Options or a
CSP to. They do ride on a rejection: a 401 from an inner
BearerTokenAuth comes back with the security headers on it, which is the
case that matters, since that response really is rendered by a browser.
Request attributes stay on the HTTP side
Section titled “Request attributes stay on the HTTP side”A middleware hands values to the handlers inside it as request attributes
— next(withAttribute(request, key, value)) — and that is how
JwtAuth delivers the claims it verified. Around a
websocket() route those values do not reach the connection: the
middleware runs inside the upgrade check, and the backend hands the
connection the upgrade request it adapted itself, so the upgrade info a hub
sees carries the path, the query and the headers, not the attributes. The
middleware still gates the handshake — a token JwtAuth refuses is
answered 401 and no socket opens.
Backend-native middleware runs too
Section titled “Backend-native middleware runs too”withMiddleware() is the portable path — it works the same on every
backend — but a handshake is also a normal request to the underlying
framework, and that framework’s own middleware runs as well:
| Backend | What also runs at the handshake |
|---|---|
| Fastify | route hooks, including preValidation |
| Express | everything registered with app.use(...) |
| Hono | everything registered with app.use(...) |
So an app that gates /ws with app.use(requireLogin) really is
gated, and a native middleware that answers the request refuses the
upgrade. The framework’s own guard runs after all of them, so
withMiddleware() and allowedOrigins always have the last word.
Prefer withMiddleware() when a route should behave identically
across backends; reach for native middleware when you are reusing an
existing ecosystem (sessions, rate limiting, observability).
WebsocketServerActor
Section titled “WebsocketServerActor”One actor per route — the hub. It sees every connection’s events, serialized:
abstract class WebsocketServerActor<TOut, TIn, TSelf = never> { // You implement: abstract onMessage(message: TIn): void | Promise<void>;
// Optional overrides: protected onClientConnected(client: WebsocketConnection<TOut>): void; protected onClientDisconnected(client: WebsocketConnection<TOut>, info: WebsocketCloseInfo): void; protected onInvalidMessage(client: WebsocketConnection<TOut>, error: WebsocketDecodeError): void; // Default: warn with the message's class, then this.unhandled(message). protected onSelfMessage(message: TSelf): void;}onSelfMessage receives what other actors tell the hub — your TSelf —
and anything else none of the hub’s own kinds matched, which includes a
body a remote node addressed to the hub’s path. Unless you override it,
it declines: a warn naming the message’s class, never its payload, then
this.unhandled(message),
so the message becomes a dead letter naming
the hub and is counted in actor_unhandled_total{class}.
A body that merely spells one of the hub’s own kinds lands here as well.
The hub recognises its signals by fields only the framework can supply —
a live connection, the factory that spawns one — and a decoded peer body
carries neither, so { kind: 'websocket-connected', … } from the wire
cannot plant a client, run onMessage or evict a connection.
Helpers
Section titled “Helpers”Inside onMessage and the hooks, these are available:
| Member | What it does |
|---|---|
this.connection | The WebsocketConnection<TOut> whose event is being processed. |
this.reply(message) | Send message to the current connection. |
this.broadcast(message, filter?) | Send to every connection (optionally filtered by predicate). |
this.clients | ReadonlyMap<string, WebsocketConnection<TOut>> of all live connections. |
this.closeAll(code?, reason?) | Close every connection. |
onMessage(message: ClientMessage): void { this.reply({ kind: 'system', text: 'got it' }); // → the sender this.broadcast({ kind: 'chat', from: 'x', text: 'hi' }); // → everyone this.broadcast(notice, (c) => c.id !== this.connection.id); // → everyone else}Per-connection ordering
Section titled “Per-connection ordering”Every event for a given connection is serialized through the one hub actor in this order:
onClientConnected → onMessage* (in frame order) → onClientDisconnectedonClientConnected runs once, then zero or more onMessage
calls in frame order, then exactly one onClientDisconnected.
Because it all runs on a single actor, you get the actor model’s
usual guarantee — no concurrent handler execution, no locks.
Across connections the hub keeps arrival order too, with one exception:
a new connection’s setup — the command that spawns its actor, and its
onClientConnected — is handled ahead of frames other connections have
already queued, so it never waits for their backlog. See
Bounding the hub’s mailbox.
Bounding the hub’s mailbox
Section titled “Bounding the hub’s mailbox”One hub carries every inbound frame from every connection on the route, which makes it the textbook case for bounding a mailbox: an actor exposed to a producer you do not control. It is also where the framework’s own connection traffic rides, and that traffic is not treated like the frames.
A hub has a control lane by default. Unless you spawn it with a
mailbox of your own, its queue is a
ControlAwareMailbox,
and two of the framework’s messages are its control messages: the
command that spawns a connection’s actor once the upgrade has completed,
and the onClientConnected signal that actor reports. Both are handled
ahead of everything already queued — other connections’ frames and your
own TSelf messages alike — so a new connection never waits for another
connection’s backlog to drain. Everything else keeps arrival order,
which is why the order per connection still holds: a connection’s
onClientDisconnected runs after its own queued frames.
A bound sheds the rest, never those two. Bound the hub with
withMailboxCapacity(), with an
actor-ts.deployment entry
for its path ("/user/chat") where its spawn site is not yours to edit, or
let actor-ts.mailbox.default.capacity reach it — in that order of
precedence — and the bound applies to frames, onClientDisconnected and
your TSelf messages; the spawn command and onClientConnected are neither
counted nor shed. A bounded hub under load therefore still accepts every
upgrade and lists every new client in this.clients, while a flood is
cut down to the capacity. What it can still lose is a disconnect, which
leaves a client in this.clients after it has gone — that part is your
protocol, and only you know whether losing one is acceptable.
The spawn command is the one that must not be lost. It is sent exactly
once, from the backend’s upgrade callback, and it carries the only
reference to a socket whose handshake has already completed. Losing it
would leave that socket upgraded with nothing attached to it: no
listeners, inbound frames piling up unread, and its maxConnections
slot held until the client gave up. A hub that cannot answer for a
different reason — it has stopped, or it never gets to the command — is
caught by the connection setup window
instead, which closes the socket and gives the slot back.
withMailbox(...) replaces the queue, and the lane with it. A hub
spawned with a mailbox of its own keeps exactly that mailbox, and the
order it gives everything: on a plain FIFO queue the spawn command waits
its turn behind every frame queued before it. It still cannot be shed —
it takes the lane a death-watch Terminated takes, which drop-head,
drop-new, reject and a PriorityMailbox all leave alone — but
onClientConnected is an ordinary message there, and a bound built into
that mailbox can drop it.
To keep strict arrival order for everything, give the hub a FIFO mailbox of its own — and bound it, because the hub is the actor its peers feed:
const chatMailboxOptions = BoundedMailboxOptions.create() .withCapacity(1_024) .withOverflow('drop-head');const chatOptions = ActorOptions.create().withMailbox(() => new BoundedMailbox(chatMailboxOptions));const chat = system.spawn(ChatRoom, 'chat', chatOptions);A mailbox you supply brings its own bound, and no other bound reaches it:
ActorOptions refuses withMailboxCapacity() beside withMailbox(), and
neither actor-ts.mailbox.default.capacity nor an actor-ts.deployment
entry applies to it. withMailbox(() => new Mailbox()) keeps the order
too, but unbounded — a hub that was bounded through the global default
loses that bound without a word.
The hub is not the only queue in play. Each connection has a mailbox of
its own — the internal connection actor’s — and connection.tell,
sendRaw and close all go into that one. It is unbounded by default,
and a route bounds it with withConnectionMailboxCapacity, plus
withConnectionMailboxOverflow for the policy — or, for every route that
does not say otherwise, the connection-mailbox-capacity and
connection-mailbox-overflow leaves under actor-ts.http.websocket:
const chatRouteOptions = WebsocketRouteOptions.create() .withConnectionMailboxCapacity(256) .withConnectionMailboxOverflow('drop-head');websocket('/chat', chat, chatRouteOptions);A route that sets neither leaves its connections to the configuration. A
"/user/<hub>/ws-*" entry under actor-ts.deployment bounds one hub’s
connections — the hub names them ws-1, ws-2, … below its own path —
and under that entry actor-ts.mailbox.default is the bound that reaches
every application actor at once.
With that global bound switched on, a route value is how one route’s
connections get a size of their own, larger or smaller; it cannot exempt
them from a bound altogether, where an entry’s mailbox-capacity = 0 can.
The route values sit above both. The policy needs a capacity beside it,
from the route or its leaf; a configured capacity — global or per path —
does not count, and the route is refused at bind() rather than at its
first upgrade.
A bound sheds outbound frames, exactly as one on the hub sheds inbound
ones. drop-head drops the oldest queued frame, drop-new the arriving
one, and reject refuses the arriving one by throwing MailboxFullError
on the sender’s stack. For reply and broadcast that stack is the
hub’s, so both catch the refusal per connection: the frame is lost for
that connection alone and counted the way drop-new would count it, and
broadcast carries on with the next client. One connection that has
fallen behind cannot fail the hub, and with it every other connection. A
connection.tell you make yourself still gets the MailboxFullError —
that is what reject is for, a sender that wants to know. What a bound
never sheds is close(): it takes the same exempt lane the accept
command does, so closeAll() cannot become a set of sockets that quietly
stay open, and reject cannot throw out of the middle of that loop and
leave every client after the first one connected. A shed frame is counted
in actor_mailbox_dropped_total; it is not dead-lettered.
WebsocketConnection
Section titled “WebsocketConnection”Each connection is a WebsocketConnection<TOut>, which extends
ActorRef<TOut>:
interface WebsocketConnection<TOut> extends ActorRef<TOut> { readonly id: string; readonly remoteAddress?: string; readonly upgrade: WebsocketUpgradeInfo; readonly isOpen: boolean; tell(message: TOut): void; // encode via codec + send sendRaw(frame: WebsocketFrame): void; // bypass the codec close(code?: number, reason?: string): void; // after what is already queued abort(code?: number, reason?: string): void; // now, dropping what is queued}close() is a request, not an act: it queues a command the connection’s
own actor runs on a later turn, so anything already queued ahead of it —
a goodbye you just reply-ed — is still written first. That ordering is
deliberate. Reply-then-close is the shape close() exists for, and a
close that jumped the queue would lose the reply, because a connection
writes nothing once it has closed.
abort() is the close that does not wait, for a peer you have stopped
serving: close(1008) would first hand a flooding client everything
already queued for it. abort() acts before it returns. The frames
still queued for the connection are dropped — they become
dead letters, never writes — and the socket
is shut on the spot. Where the backend can hard-close a socket, as the
ws-backed Fastify and Express backends can, and Hono can under Bun
and Node, the peer sees the connection drop without a close frame; on
Hono under Deno, whose socket has no hard close, it receives a close
frame with your code and reason. The hub still gets exactly one
onClientDisconnected, carrying that code and reason with
initiatedBy: 'server', and it still comes last: frames the peer sent
before the abort that are already queued for the hub reach onMessage
first. On a connection that is no longer open — after
close(), after an earlier abort(), or once the client has gone —
abort() does nothing, so the first decision about a socket stands.
Its code defaults to 1008, policy violation, where close()’s defaults
to 1000.
A close frame carries a code from a fixed set and at most 123 bytes of
reason, and both methods send only that. A code outside 1000–1014 and
3000–4999, or one of the codes reserved for reporting a close (1004,
1005, 1006), goes out as the method’s own default — 1000 for close(),
1008 for abort() — and a longer reason is cut to 123 UTF-8 bytes,
between two characters. onClientDisconnected still reports the code
and reason you passed. Handed straight to the transport, either one
left the socket open on some backends while the hub was told it had
closed: the ws package refuses the close after it has already started
it, and Deno’s socket refuses it outright. Should a backend’s close
fail anyway, the socket is hard-closed where the backend can; where it
cannot, a warning names the connection.
isOpen reads false as soon as close() or abort() returns — after
close(), before the socket has actually shut — so broadcast and your
own if (client.isOpen) checks stop selecting a peer you have already
decided to disconnect.
upgrade carries the handshake context:
type WebsocketUpgradeInfo = { path: string; params: Record<string, string>; query: Record<string, string | string[] | undefined>; headers: Record<string, string>; remoteAddress?: string; subprotocol?: string;};WebsocketCloseInfo (passed to onClientDisconnected) is
{ code: number; reason: string; initiatedBy: 'client' | 'server' | 'error' }.
Codecs
Section titled “Codecs”The route codec decodes inbound frames into TIn and encodes
TOut replies. Default is jsonCodec():
import { WebsocketRouteOptions, jsonCodec } from 'actor-ts/http';
const webSocketRouteOptions = WebsocketRouteOptions.create().withCodec(jsonCodec<ServerMessage, ClientMessage>({ validate: (v: unknown): ClientMessage => ClientMsgSchema.parse(v), }));websocket('/ws', chat, webSocketRouteOptions);For binary protocols, rawCodec() gives you raw frames
(TOut = TIn = WebsocketFrame):
import { match } from 'ts-pattern';import { rawCodec, WebsocketRouteOptions, WebsocketServerActor, type WebsocketFrame,} from 'actor-ts/http';
const webSocketRouteOptions = WebsocketRouteOptions.create().withCodec(rawCodec());class BinaryHub extends WebsocketServerActor<WebsocketFrame, WebsocketFrame> { onMessage(frame: WebsocketFrame): void { match(frame) .with({ kind: 'binary' }, (f) => this.onBinary(f)) .otherwise(() => {}); }
private onBinary(frame: BinaryFrame): void { this.reply({ kind: 'binary', data: process(frame.data) }); }}
websocket('/stream', binaryHub, webSocketRouteOptions);Decode failures throw WebsocketDecodeError and follow the route’s
onInvalidMessage policy.
Backends and runtimes
Section titled “Backends and runtimes”websocket() works on all three HTTP backends:
| Backend | Peer dependency | Runtime notes |
|---|---|---|
| Fastify (default) | @fastify/websocket | Runs on Bun and Node; on Deno prefer Hono. |
| Express | ws | — |
| Hono | Bun & Deno: built into hono. Hono-on-Node: @hono/node-ws. | Per-runtime helpers. |
npm install @fastify/websocket # Fastify (default)npm install ws # Expressnpm install @hono/node-ws # Hono on Node only, 1.2.0 or newerHOCON config
Section titled “HOCON config”Route defaults live under actor-ts.http.websocket:
actor-ts.http.websocket { max-frame-bytes = 1M on-oversize-frame = "close" on-invalid-message = "close" max-buffered-bytes = 4M on-backpressure = "drop" max-pre-attach-frames = 256 max-pre-attach-bytes = 4M accept-timeout = 10s # Unset by default; a route's own value wins over both. # connection-mailbox-capacity = 256 # connection-mailbox-overflow = "drop-head"}Precedence: route options > HOCON > built-in defaults. The two
connection-mailbox-* leaves have no built-in default: unset, the
connection actor falls through to the actor-ts.deployment entry matching
its path ("/user/<hub>/ws-*"), then to actor-ts.mailbox.default.
Each leaf is the kebab-case of its WebsocketRouteOptions field with any unit
suffix dropped — the field stays acceptTimeoutMs, the leaf is
accept-timeout, and the value carries the unit. The camelCase spellings
this block used before are rejected at bind() with a ConfigError naming
both, rather than ignored: most of these leaves are caps a semi-trusted
deployment lowers on purpose, and a cap that silently reverted to the
framework default is worse than one that refuses to start.
When to use it
Section titled “When to use it”Three good fits:
- Real-time UIs — pushing updates to browser clients.
- Custom messaging protocols — game servers, chat backends.
- Binary streaming — use
rawCodec()and handle frames directly.
For one-way streams from server to client, SSE is simpler. For request/reply RPC, plain HTTP is the norm.
Where to next
Section titled “Where to next”- I/O overview — the bigger picture.
- WebsocketClientActor — the outbound client half.
- Route DSL —
path,concat, and howwebsocket()composes. - SSE — server-sent events, the one-way alternative.
- HTTP overview — backends, middleware, and server binding.
