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.

Back to the full Bun cheat sheet