Skip to content

WebSockets

Register WebSocket routes on host.ws, type messages with socketContract, and broadcast with channels and connection state.

AI generated, pending review Updated 10 days ago · Flare 0.3

The WebSocket arc lives on host.ws. Register inline handlers or controller classes, declare message shapes with socketContract, and read upgrade params and inbound messages from scope.input the same way HTTP handlers read route, query, and body fields.

Without a framework in front of it, a WebSocket endpoint is a raw socket plus bookkeeping you keep by hand. You hold a set of live connections, add to it on open, and remember to remove them on close or leak a dead socket; you write the loop that fans a message out to the right subset of them; and you wrap every inbound frame in a JSON.parse and a try/catch, because one malformed message otherwise throws deep in a handler. On a Durable Object, hibernation adds a second copy of that connection state to rebuild on each wake. Flare keeps the raw socket and turns the rest into declared surface: routes are typed and matched like HTTP, channels are a broadcast domain the runtime maintains for you, and per-connection state is a contract that survives a wake.

On Node and inside a Durable Object, connections share a broadcast domain so you can publish from HTTP handlers with WebSocketChannels. On a plain Cloudflare Worker, each socket stays pinned to the request that accepted it, so channels are not available on the front door.

See The arc model for how the WebSocket arc fits next to HTTP and Durable Objects. Signatures live in the API Reference.

  • Overview: host.ws.route and host.ws.controller; upgrade matching and lifecycle hooks.
  • Inline handlers: Function-form routes with open, message, close, and error behaviors.
  • Controller classes: WebSocketControllerBase subclasses with static deps and contract.
  • Contracts: socketContract entries for incoming, outgoing, params, and query.
  • Channels and broadcast: Subscribe at open and publish from handlers or HTTP routes.
  • Connection state: Per-connection ws.state that survives Durable Object hibernation.