WebSocket Server in Bun
From the Bun cheat sheet ยท WebSockets ยท verified Jul 2026
WebSocket Server
Add WebSocket support to Bun.serve with handlers and pub/sub
typescript
Bun.serve({
fetch(req, server) {
if (server.upgrade(req)) return; // Upgrade to WS
return new Response("Not a WS request", { status: 400 });
},
websocket: {
open(ws) { ws.send("Welcome!"); },
message(ws, msg) { ws.send(`Echo: ${msg}`); },
close(ws) { console.log("Disconnected"); },
},
});๐ก Bun WebSockets handle 4x more messages per second than Node.js ws package
โก Built-in pub/sub with ws.subscribe/publish โ no Redis or external broker needed
๐ Pass per-socket data in server.upgrade() โ access it later via ws.data
๐ข WebSocket handlers are defined alongside HTTP routes in the same Bun.serve() call
websocketrealtimepubsub
Continue with Bun
Save the full cheat sheet or work through every related task.