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;Typorithm · medium
Step 1 of 8 · intro card
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.
server.upgrade(req) turns the request into a WebSocket.
websocket defines open, message, and close handlers.
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");
},
},
});Connect each part of the code to the concept before you type.
server.upgrade(req) switches the HTTP request to a WebSocket; returning early hands the socket to the websocket handlers.
if (server.upgrade(req)) return;The websocket object holds the open, message, and close callbacks for the live connection.
websocket: {open(ws) runs once when a client finishes the upgrade, a good place to subscribe.
open(ws) {ws.subscribe(topic) joins this socket to a pub/sub topic so it receives published messages.
ws.subscribe("room");server.publish(topic, data) broadcasts to every socket subscribed to that topic.
server.publish("room", msg);Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.