Skip to main content
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 + "ws".Internally Bun’s WebSocket implementation is built on uWebSockets.

Start a WebSocket server

Below is a WebSocket server built with Bun.serve, in which all incoming requests are upgraded to WebSocket connections in the fetch handler. The socket handlers are declared in the websocket parameter.
server.ts
The following WebSocket event handlers are supported:
server.ts
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
So, instead of using an event-based API, 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.
The first argument to each handler is the instance of ServerWebSocket handling the event. The ServerWebSocket class is a fast, Bun-native implementation of WebSocket with some additional features.
server.ts

Sending messages

Each ServerWebSocket instance has a .send() method for sending messages to the client. It supports a range of input types.
server.ts

Headers

Once the upgrade succeeds, Bun will send a 101 Switching Protocols response per the spec. Additional headers can be attached to this Response in the call to server.upgrade().
server.ts

Contextual data

Contextual data 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. To strongly type ws.data, add a data property to the websocket handler object. This types ws.data across all lifecycle hooks.
server.ts
Note: Previously, you could specify the type of ws.data using 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 shown above.
To connect to this server from the browser, create a new 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’s ServerWebSocket 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.
server.ts
Calling .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 the perMessageDeflate parameter.
server.ts
Compression can be enabled for individual messages by passing a boolean as the second argument to .send().
For fine-grained control over compression characteristics, refer to the Reference.

Backpressure

The .send(message) method of ServerWebSocket returns a number indicating the result of the operation.
  • -1 — The message was enqueued but there is backpressure
  • 0 — The message was dropped due to a connection issue
  • 1+ — The number of bytes sent
This gives you better control over backpressure in your server.

Timeouts and limits

By default, Bun will close a WebSocket connection if it is idle for 120 seconds. This can be configured with the idleTimeout parameter.
Bun will also close a WebSocket connection if it receives a message that is larger than 16 MB. This can be configured with the 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.
In browsers, the cookies that are currently set on the page will be sent with the WebSocket upgrade request. This is a standard feature of the 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.
To add event listeners to the socket:

Reference

See Typescript Definitions