Documentation Index
Fetch the complete documentation index at: https://mintlify.com/zhcndoc/bun/llms.txt
Use this file to discover all available pages before exploring further.
Bun’s WebSocket implementation includes built-in pub/sub support.
Pub/Sub Server
Bun.serve({
fetch(req, server) {
server.upgrade(req);
},
websocket: {
open(ws) {
ws.subscribe("chat");
},
message(ws, message) {
// Publish to all subscribers
ws.publish("chat", message);
},
},
});
Multiple Channels
Bun.serve({
websocket: {
open(ws) {
ws.subscribe("lobby");
},
message(ws, message) {
const data = JSON.parse(message);
if (data.action === "join") {
ws.subscribe(data.channel);
ws.send(JSON.stringify({ joined: data.channel }));
} else if (data.action === "send") {
ws.publish(data.channel, data.message);
}
},
},
});
See WebSocket API for complete documentation.