Typorithm · medium

WebSockets

bun-websocketbunwebsocketpubsubupgrade
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn WebSockets

0%

Web & Sockets

In the fetch handler, server.upgrade(req) turns an HTTP request into a WebSocket and you return early on success. The websocket object defines open, message, and close. Pub/sub is built in: ws.subscribe(topic) joins a topic and server.publish(topic, data) broadcasts to all subscribers.

WebSockets start as a normal HTTP request. Inside fetch(req, server) you call server.upgrade(req); if it returns true the connection became a socket and you return early so Bun routes it to the websocket handlers.

The websocket object holds the lifecycle callbacks: open(ws) fires once on connect, message(ws, msg) on each inbound frame, and close(ws) when the socket ends.

Bun has built-in pub/sub: ws.subscribe("room") joins a socket to a topic and server.publish("room", msg) broadcasts a message to every subscriber of that topic, so a chat room is a few lines.

01

server.upgrade(req) turns the request into a WebSocket.

02

websocket defines open, message, and close handlers.

03

ws.subscribe(topic) + server.publish(topic, data) is built-in pub/sub.

Bun.serve({
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return new Response("upgrade failed", { status: 500 });
  },
  websocket: {
    open(ws) {
      ws.subscribe("room");
    },
    message(ws, msg) {
      server.publish("room", msg);
    },
    close(ws) {
      ws.unsubscribe("room");
    },
  },
});

Read the implementation

Connect each part of the code to the concept before you type.

1. Upgrade request

server.upgrade(req) switches the HTTP request to a WebSocket; returning early hands the socket to the websocket handlers.

if (server.upgrade(req)) return;

2. Socket handlers

The websocket object holds the open, message, and close callbacks for the live connection.

websocket: {

3. On open

open(ws) runs once when a client finishes the upgrade, a good place to subscribe.

open(ws) {

4. Subscribe

ws.subscribe(topic) joins this socket to a pub/sub topic so it receives published messages.

ws.subscribe("room");

5. Publish

server.publish(topic, data) broadcasts to every socket subscribed to that topic.

server.publish("room", msg);

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

WebSockets: Lesson & Practice · Typorithm | ApplyDjinn