Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 39 ยท HTTP Servers and APIs

WebSockets and Pub/Sub

Build real-time features with Bun's built-in WebSocket server: server.upgrade, open/message/close handlers, per-socket data, topics with subscribe and publish, and a runnable chat stand-in.

HTTP is request and response: the client asks, the server answers. A WebSocket is a long-lived two-way connection, so either side can send a message at any time. Use it for chat, multiplayer games, collaborative editing and live prices. Bun has a WebSocket server built into Bun.serve, with a pub/sub system on top that makes "send this to everyone in room X" a single call.

Upgrading a request

A WebSocket starts life as a normal HTTP request with an Upgrade: websocket header. Your fetch handler decides whether to accept it by calling server.upgrade(req). If it returns true, Bun takes over the connection and you return nothing.

TypeScript
type SocketData = { user: string };

Bun.serve<SocketData>({
  fetch(req, server) {
    const url = new URL(req.url);
    if (url.pathname === "/chat") {
      const user = url.searchParams.get("user") ?? "guest";
      const ok = server.upgrade(req, { data: { user } });
      if (ok) return; // upgraded: no Response needed
      return new Response("Upgrade failed", { status: 400 });
    }
    return new Response("Normal HTTP still works here");
  },
  websocket: {
    open(ws) {
      console.log(ws.data.user, "connected");
    },
    message(ws, message) {
      ws.send(`echo from ${ws.data.user}: ${message}`);
    },
    close(ws, code, reason) {
      console.log(ws.data.user, "left", code, reason);
    },
  },
});

The websocket object has one set of handlers shared by all connections (unlike browsers, where every socket has its own callbacks). That is why Bun uses less memory per connection. To tell sockets apart, attach per-connection data during upgrade and read it as ws.data; the generic Bun.serve<SocketData> makes it typed.

The handlers:

  • open(ws) when the handshake is done.
  • message(ws, message) with a string for text frames or a Buffer for binary.
  • close(ws, code, reason) when it ends (code 1000 is a normal close).
  • drain(ws) when a socket that was backed up can accept data again.
  • ws.send(data), ws.close(code?, reason?), ws.readyState, ws.remoteAddress.

Check the user in fetch before upgrading (cookie, token in the query string, Origin header): once the socket is open there is no HTTP request to authenticate any more. Also validate the Origin header, because browsers do not enforce the same-origin policy for WebSockets.

Pub/Sub

Without pub/sub you would keep your own Set of sockets and loop over it. Bun does this natively with topics. A socket subscribes to a topic; anyone can publish to it, and every subscriber gets the message.

TypeScript
Bun.serve<{ room: string; user: string }>({
  fetch(req, server) {
    const url = new URL(req.url);
    const room = url.searchParams.get("room") ?? "lobby";
    const user = url.searchParams.get("user") ?? "guest";
    if (server.upgrade(req, { data: { room, user } })) return;
    return new Response("Expected a WebSocket", { status: 426 });
  },
  websocket: {
    open(ws) {
      ws.subscribe(ws.data.room);
      ws.publish(ws.data.room, `${ws.data.user} joined`);
    },
    message(ws, message) {
      // publish goes to everyone subscribed EXCEPT the sender
      ws.publish(ws.data.room, `${ws.data.user}: ${message}`);
      ws.send(`you: ${message}`);
    },
    close(ws) {
      ws.publish(ws.data.room, `${ws.data.user} left`);
      // subscriptions are removed automatically on close
    },
  },
});

Two publish functions exist. ws.publish(topic, data) skips the sender. server.publish(topic, data) goes to everyone, and it can be called from anywhere (an HTTP route, a timer, a queue consumer), which is how a background job pushes a notification to browsers.

Other useful options: maxPayloadLength (reject giant messages), idleTimeout (seconds of silence before closing, default 120), perMessageDeflate: true (compress messages) and backpressureLimit. Browsers cannot send custom headers on new WebSocket(url), so authentication usually uses a cookie or a short-lived token in the URL.

A chat room you can run

Bun itself is not available here. The stand-in below simulates the pub/sub core (topics, subscribe, publish that skips the sender, shared handlers, per-socket data) with plain objects, so you can study the logic that Bun implements natively.

Node.js Pub/sub rooms: a stand-in for ws.subscribe / ws.publish

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The browser side

The client uses the standard WebSocket class:

JavaScript
const ws = new WebSocket("wss://example.com/chat?room=dev&user=ada");
ws.addEventListener("open", () => ws.send("hello"));
ws.addEventListener("message", (e) => console.log("got", e.data));
ws.addEventListener("close", (e) => console.log("closed", e.code));

Bun also provides the same WebSocket class on the client side, so a Bun script can connect to any server, and you can test your server from bun test (testing). Real clients must reconnect with a growing delay after an unexpected close, and send an application-level ping if proxies drop idle connections.

Design tips

  • Send JSON messages with a type field ({ "type": "chat", "text": "hi" }) and validate them like any other request body.
  • Rate-limit messages per socket; one bad client can flood a room.
  • Pub/sub works inside one process. With several servers behind a load balancer, bridge topics through Redis or another broker.
  • Store history in a database, not in socket memory, so new joiners can load the last messages.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do you return from fetch after server.upgrade(req) returns true?

    After a successful upgrade Bun owns the connection, so the handler just returns.
  2. 2. How do Bun's WebSocket handlers differ from the browser's?

    Sharing handlers saves memory; use data in upgrade to attach identity per connection.
  3. 3. What is the difference between ws.publish and server.publish?

    ws.publish excludes the sender; server.publish sends to everyone subscribed.
  4. 4. Where should you authenticate a WebSocket user?

    After the upgrade there is no HTTP request left to check cookies or headers; decide first.

Summary

  • Accept connections with server.upgrade(req, { data }) inside fetch; Bun then calls shared open, message, close, drain handlers.
  • Per-connection state lives in ws.data; authenticate and check Origin before upgrading.
  • ws.subscribe(topic), ws.publish(topic, msg) and server.publish(topic, msg) implement rooms natively.
  • Set maxPayloadLength and rate limits; use a broker when scaling past one process.
  • Clients use the standard WebSocket and should reconnect with backoff.

Next: Your First Tests with bun test