Files
bun.sh/docs/guides/websocket/pubsub.md
Alistair Smith b22e19baed [1.3] Bun.serve({ websocket }) types (#20918)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2025-10-06 16:07:36 -07:00

42 lines
1.3 KiB
Markdown

---
name: Build a publish-subscribe WebSocket server
---
Bun's server-side `WebSocket` API provides a native pub-sub API. Sockets can be subscribed to a set of named channels using `socket.subscribe(<name>)`; messages can be published to a channel using `socket.publish(<name>, <message>)`.
This code snippet implements a simple single-channel chat server.
```ts
const server = Bun.serve({
fetch(req, server) {
const cookies = req.headers.get("cookie");
const username = getUsernameFromCookies(cookies);
const success = server.upgrade(req, { data: { username } });
if (success) return undefined;
return new Response("Hello world");
},
websocket: {
// TypeScript: specify the type of ws.data like this
data: {} as { username: string },
open(ws) {
const msg = `${ws.data.username} has entered the chat`;
ws.subscribe("the-group-chat");
server.publish("the-group-chat", msg);
},
message(ws, message) {
// the server re-broadcasts incoming messages to everyone
server.publish("the-group-chat", `${ws.data.username}: ${message}`);
},
close(ws) {
const msg = `${ws.data.username} has left the chat`;
server.publish("the-group-chat", msg);
ws.unsubscribe("the-group-chat");
},
},
});
console.log(`Listening on ${server.hostname}:${server.port}`);
```