# Build a publish-subscribe WebSocket server (/docs/guides/websocket/pubsub)

<!-- agent-signals: reading_time_min: 1 · est_tokens: 328 · updated: 2026-07-28 -->
Related: [Build a simple WebSocket server](/docs/guides/websocket/simple.md), [Set per-socket contextual data on a WebSocket](/docs/guides/websocket/context.md), [Enable compression for WebSocket messages](/docs/guides/websocket/compression.md)

Bun's server-side `WebSocket` API includes native pub-sub. Subscribe a socket to a set of named channels with `socket.subscribe(<name>)`; publish a message to a channel with `socket.publish(<name>, <message>)`.

This code snippet implements a single-channel chat server.

```ts server.ts icon="/icons/typescript.svg"
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}`);
```
