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
Below is a simple WebSocket server built withBun.serve, in which all incoming requests are upgraded to WebSocket connections 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.
ServerWebSocket expects you to pass a WebSocketHandler object to the Bun.serve() method which has methods for open, message, close, drain, and error. This is different than the client-side WebSocket class which extends EventTarget (onmessage, onopen, onclose),Clients tend to not have many socket connections open so an event-based API makes sense.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 callbacks function for each connection
- Usually, people create new functions for each connection, which also means more memory
ServerWebSocket expects you to pass a single object with methods for each event in Bun.serve() and it is reused for each connection.This leads to less memory usage and less time spent adding/removing event listeners.ServerWebSocket 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 will send a101 Switching Protocols response per the spec. Additional headers can be attached to this Response in the call to server.upgrade().
Contextual data
Contextualdata can be attached to a new WebSocket in the .upgrade() call. This data is made available on the ws.data property inside the WebSocket handlers.
WebSocket.
browser.js
Identifying usersThe cookies that are currently set on the page will be sent with the WebSocket upgrade request and available on
req.headers in the fetch handler. Parse these cookies to determine the identity of the connecting user and set the value of data accordingly.Pub/Sub
Bun’sServerWebSocket implementation implements 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) will send 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
Per-message compression can be enabled 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 will close a WebSocket connection if it is idle for 120 seconds. This can be configured 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.
For convenience, Bun lets you setting custom headers directly in the constructor. This is a Bun-specific extension of the WebSocket standard. This will not work in browsers.
Reference
See Typescript Definitions