Bun.serve() supports server-side WebSockets, with on-the-fly compression, TLS support, and a Bun-native publish-subscribe API.
⚡️ 7x more throughputBun’s WebSockets are fast. For a simple chatroom on Linux x64, Bun can handle 7x more requests per second than Node.js +
Internally Bun’s WebSocket implementation is built on uWebSockets.
"ws".| Messages sent per second | Runtime | Clients |
|---|---|---|
| ~700,000 | (Bun.serve) Bun v0.2.1 (x64) | 16 |
| ~100,000 | (ws) Node v18.10.0 (x64) | 16 |
Start a WebSocket server
The following server, built withBun.serve, upgrades every incoming request to a WebSocket connection in the fetch handler. The socket handlers are declared in the websocket parameter.
An API designed for speed
An API designed for speed
In Bun, handlers are declared once per server, instead of per socket.You pass a single
WebSocketHandler object to Bun.serve() with methods for open, message, close, drain, and error. This is different from the client-side WebSocket class, which extends EventTarget (onmessage, onopen, onclose).Clients tend to have few socket connections open, so an event-based API makes sense there.But servers tend to have many socket connections open, which means:- Time spent adding/removing event listeners for each connection adds up
- Extra memory spent on storing references to callback functions for each connection
- Usually, people create new functions for each connection, which also means more memory
ServerWebSocket instance handling the event. The ServerWebSocket class is a fast, Bun-native implementation of WebSocket with some additional features.
Sending messages
EachServerWebSocket instance has a .send() method for sending messages to the client. It supports a range of input types.
Headers
Once the upgrade succeeds, Bun sends a101 Switching Protocols response per the spec. To attach additional headers to this Response, pass them to server.upgrade().
Contextual data
Attach contextualdata to a new WebSocket in the .upgrade() call. It is available on the ws.data property inside the WebSocket handlers.
To strongly type ws.data, add a data property to the websocket handler object. This types ws.data across all lifecycle hooks.
Previously, you could specify the type of
ws.data with a type parameter on Bun.serve, like Bun.serve<MyData>({...}). This pattern was removed due to a limitation in TypeScript in favor of the data property.WebSocket.
browser.js
Identifying usersCookies set on the page are sent with the WebSocket upgrade request and available on
req.headers in the fetch handler. Parse them to identify the connecting user and set data accordingly.Pub/Sub
Bun’sServerWebSocket includes a native publish-subscribe API for topic-based broadcasting. Individual sockets can .subscribe() to a topic (specified with a string identifier) and .publish() messages to all other subscribers to that topic (excluding itself). This topic-based broadcast API is similar to MQTT and Redis Pub/Sub.
.publish(data) sends the message to all subscribers of a topic except the socket that called .publish(). To send a message to all subscribers of a topic, use the .publish() method on the Server instance.
Compression
Enable per-message compression with theperMessageDeflate parameter.
boolean as the second argument to .send().
Backpressure
The.send(message) method of ServerWebSocket returns a number indicating the result of the operation.
-1— The message was enqueued but there is backpressure0— The message was dropped due to a connection issue1+— The number of bytes sent
Timeouts and limits
By default, Bun closes a WebSocket connection that has been idle for 120 seconds. Configure this with theidleTimeout parameter.
maxPayloadLength parameter.
Connect to a Websocket server
Bun implements the WebSocket class. To create a WebSocket client that connects to a ws:// or wss:// server, create an instance of WebSocket, as you would in the browser.
WebSocket API.
In Bun, you can also set custom headers directly in the constructor. This is a Bun-specific extension of the WebSocket standard. It does not work in browsers.
Reference
See Typescript Definitions