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 awebsocket object to Bun.serve(). Upgrade HTTP connections to WebSocket in the fetch handler by calling server.upgrade(req).
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 onws.data inside all lifecycle handlers. Add a typed data property to the websocket object for full TypeScript inference.
Custom upgrade headers
Attach headers to the101 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.Counting subscribers
Compression
Enable per-message deflate compression globally on thewebsocket handler:
true as the second argument to ws.send():
compress and decompress separately:
"disable", "shared", "dedicated", "3KB" through "256KB".
Timeouts and limits
WebSocket client
Bun implements the standard browserWebSocket API. Connect to any ws:// or wss:// server:
Custom headers (Bun extension)
Bun allows setting custom HTTP headers directly in theWebSocket constructor. This is a Bun-specific extension and does not work in browsers.