Skip to main content
Bun.serve() has first-class support for server-side WebSockets with on-the-fly compression, TLS, and a built-in publish-subscribe API — all powered by uWebSockets.
Bun’s WebSocket server handles ~700,000 messages/second with 16 clients on Linux x64, compared to ~100,000 messages/second with Node.js + ws.

Basic WebSocket server

Pass a websocket object to Bun.serve(). Upgrade HTTP connections to WebSocket in the fetch handler by calling server.upgrade(req).
The four lifecycle handlers are:
Handlers are declared once per server and shared across all connections. This keeps memory usage flat regardless of how many clients are connected.

Sending messages

ws.send() accepts strings, ArrayBuffer, and TypedArray/DataView values. It returns a status number:
  • 1+ — bytes sent
  • -1 — message enqueued (backpressure)
  • 0 — message dropped (connection issue)

Contextual data

Attach arbitrary data to a connection during upgrade. The data is available on ws.data inside all lifecycle handlers. Add a typed data property to the websocket object for full TypeScript inference.

Custom upgrade headers

Attach headers to the 101 Switching Protocols response by passing a headers object to server.upgrade():

Pub/Sub

Bun provides a native topic-based publish-subscribe API. Sockets subscribe to named topics and publish messages that are broadcast to all other subscribers of that topic.
Call server.publish(topic, message) (on the Server object) to send to all subscribers including the calling socket. Call ws.publish(topic, message) to send to all subscribers except the calling socket.

Counting subscribers


Compression

Enable per-message deflate compression globally on the websocket handler:
Compress individual messages by passing true as the second argument to ws.send():
For fine-grained control, configure compress and decompress separately:
Valid compressor values: "disable", "shared", "dedicated", "3KB" through "256KB".

Timeouts and limits


WebSocket client

Bun implements the standard browser WebSocket API. Connect to any ws:// or wss:// server:

Custom headers (Bun extension)

Bun allows setting custom HTTP headers directly in the WebSocket constructor. This is a Bun-specific extension and does not work in browsers.

Subprotocol negotiation


Reference