WebSocket Integration
By the end of this lesson you will be able to explain what happens during a WebSocket handshake, run a small Node.js live-score server, and write a browser client that reconnects politely, detects dead connections with heartbeats and announces big moments to screen reader users.
What you should know first: Fetch API Integration for requests and JSON, and HTML Web APIs for the idea of live updates. The JavaScript course lesson WebSockets & Server-Sent Events covers the basic events, send() and close codes. This lesson starts where it stops.
The handshake: an HTTP request that changes into something else
A WebSocket begins life as an ordinary HTTP GET request. The browser adds headers that ask the server to switch protocols. If the server agrees, it answers with status 101 Switching Protocols, and the same TCP connection now carries WebSocket frames (small packets of data) in both directions.
Think of a railway enquiry counter. You queue like everyone else (HTTP), but you ask for the station master's direct line. If he agrees, you keep that line open and both of you can speak whenever you like.
This is a real exchange with the server you will build below. Other headers, such as User-Agent, are left out:
GET /live HTTP/1.1
Host: localhost:8080
Connection: Upgrade
Upgrade: websocket
Origin: http://localhost:8080
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: Y3JpY2tldC1zY29yZXMhIQ==
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: RSUKflZ5Ws2tkkxhJrN+i5ODFKc=Sec-WebSocket-Keyis 16 random bytes in Base64, made fresh by the browser for each connection.Sec-WebSocket-Acceptproves the server really speaks WebSocket. It is the SHA-1 hash of the key joined to a fixed text from RFC 6455, encoded in Base64.Originnames the site whose page opened the connection. The browser sets it and page scripts cannot change it. You will use it for security.
The key is not a password. It only stops a confused HTTP server or cache from treating the request as normal. You can calculate the answer yourself:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sec-WebSocket-Accept calculator</title>
</head>
<body>
<h1>What the server sends back</h1>
<label for="key">Sec-WebSocket-Key from the browser</label>
<input id="key" size="30" value="Y3JpY2tldC1zY29yZXMhIQ==">
<button type="button" id="calc">Calculate</button>
<button type="button" id="fresh">New random key</button>
<pre id="out"></pre>
<script>
const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // fixed by RFC 6455
async function acceptFor(key) {
const bytes = new TextEncoder().encode(key.trim() + GUID);
const hash = new Uint8Array(await crypto.subtle.digest("SHA-1", bytes));
return btoa(String.fromCharCode(...hash)); // bytes to Base64
}
async function show() {
const accept = await acceptFor(document.querySelector("#key").value);
document.querySelector("#out").textContent =
"HTTP/1.1 101 Switching Protocols\n" +
"Upgrade: websocket\n" +
"Connection: Upgrade\n" +
`Sec-WebSocket-Accept: ${accept}`;
}
document.querySelector("#fresh").addEventListener("click", () => {
const random = crypto.getRandomValues(new Uint8Array(16)); // 16 random bytes, as browsers do
document.querySelector("#key").value = btoa(String.fromCharCode(...random));
show();
});
document.querySelector("#calc").addEventListener("click", show);
show();
</script>
</body>
</html>The page shows Sec-WebSocket-Accept: RSUKflZ5Ws2tkkxhJrN+i5ODFKc=, exactly what the Node server sent. Press "New random key" to see a different pair. After the 101 response, the browser also handles ping and pong control frames for you. Your page script never sees them, which matters for heartbeats later.
Live coding: a live score server in Node.js
The Try-it editor cannot reach a WebSocket server, so this part is plain code. It was run with Node 22 and the ws package (version 8.23), installed with npm install ws. Node 22 has a built-in WebSocket client, but no server.
Step 1: create the server. It refuses unknown origins, sends the current score to each new connection, checks every incoming message and broadcasts a new ball every two seconds.
// score-server.mjs: live score + match chat over WebSocket (Node 22, ws 8)
import { createServer } from "node:http";
import { WebSocketServer } from "ws";
const ALLOWED_ORIGINS = new Set(["https://scores.example.in", "http://localhost:8080"]);
const http = createServer((req, res) => res.writeHead(404).end());
const wss = new WebSocketServer({ noServer: true, maxPayload: 4096 });
// 1. Check the Origin before accepting the upgrade
http.on("upgrade", (req, socket, head) => {
if (!ALLOWED_ORIGINS.has(req.headers.origin)) {
console.log("Refused upgrade from", req.headers.origin);
socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");
return;
}
wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req));
});
const score = { runs: 142, wickets: 3, over: "17.0" };
const send = (ws, msg) => ws.send(JSON.stringify(msg));
const broadcast = (msg) => {
for (const client of wss.clients) if (client.readyState === 1) send(client, msg);
};
// 2. Each new connection gets the current score at once
wss.on("connection", (ws, req) => {
console.log("Connected:", req.headers.origin, "| clients:", wss.clients.size);
ws.isAlive = true;
ws.on("pong", () => { ws.isAlive = true; });
send(ws, { type: "score", ...score });
// 3. Treat every message as untrusted
ws.on("message", (data) => {
let msg;
try { msg = JSON.parse(data); } catch { return ws.close(1003, "JSON only"); }
if (msg.type === "ping") return send(ws, { type: "pong" });
if (msg.type === "chat" && typeof msg.text === "string" && msg.text.length <= 200) {
console.log("Chat:", msg.text);
broadcast({ type: "chat", from: String(msg.from).slice(0, 20), text: msg.text });
}
});
ws.on("close", (code) => console.log("Closed with code", code));
});
// 4. Server heartbeat: ping every 30 s, drop clients that never answered
setInterval(() => {
for (const ws of wss.clients) {
if (!ws.isAlive) { ws.terminate(); continue; }
ws.isAlive = false;
ws.ping();
}
}, 30_000).unref();
// 5. A new ball every 2 seconds (a real app would read the scorer's feed)
const balls = [[1, "single"], [4, "FOUR through cover"], [0, "WICKET, caught at slip"]];
let ball = 102; // 17 overs bowled
setInterval(() => {
const [runs, text] = balls[ball % balls.length];
ball++;
score.runs += runs;
if (text.startsWith("WICKET")) score.wickets++;
score.over = `${Math.floor(ball / 6)}.${ball % 6}`;
broadcast({ type: "score", ...score, text });
}, 2000).unref();
http.listen(8080, () => console.log("Live score server on ws://localhost:8080"));Step 2: test it with two clients. One pretends to come from https://evil.example. The other behaves like Priya's browser tab. The ws package's WebSocket class has the same open, message and close events as the browser's, and it lets a test set the Origin header.
// test-client.mjs
import WebSocket from "ws";
const bad = new WebSocket("ws://localhost:8080", { origin: "https://evil.example" });
bad.addEventListener("error", () => console.log("evil.example: connection refused"));
const socket = new WebSocket("ws://localhost:8080", { origin: "http://localhost:8080" });
let count = 0;
socket.addEventListener("open", () => {
console.log("open, readyState", socket.readyState);
socket.send(JSON.stringify({ type: "chat", from: "Priya", text: "Kohli on strike?" }));
});
socket.addEventListener("message", (event) => {
const msg = JSON.parse(event.data);
if (msg.type === "score") console.log(`${msg.runs}/${msg.wickets} (${msg.over})${msg.text ? " " + msg.text : ""}`);
if (msg.type === "chat") console.log(`${msg.from}: ${msg.text}`);
if (++count === 5) socket.close(1000, "Match over for me");
});
socket.addEventListener("close", (event) => console.log("close", event.code, event.reason));The client printed this (the order of the first lines can change, because the ball timer runs on its own):
open, readyState 1 142/3 (17.0) 143/3 (17.1) single Priya: Kohli on strike? evil.example: connection refused 147/3 (17.2) FOUR through cover 147/4 (17.3) WICKET, caught at slip close 1000 Match over for me
And the server terminal showed:
Live score server on ws://localhost:8080 Connected: http://localhost:8080 | clients: 1 Refused upgrade from https://evil.example Chat: Kohli on strike? Closed with code 1000
Reconnecting without crushing the server
A WebSocket never reconnects by itself. When a stadium's Wi-Fi blinks, thousands of fans drop together. If every app retries at exactly 1, 2 and 4 seconds, they all hit the server together, again and again. Two fixes work together:
- Exponential backoff: double the wait after each failure, up to a limit such as 15 or 30 seconds.
- Jitter: multiply the wait by a random number, so clients spread out. A tiffin dabbawala does not send every runner through one gate at the same second.
Reset the attempt counter in open, and never reconnect after your own close(1000). After a reconnect, ask for (or receive) a full snapshot of the state, because you missed messages while you were away.
Heartbeats: noticing a dead line
Sometimes a connection dies silently. A phone moves from Wi-Fi to mobile data, or a router forgets the connection. readyState still says 1 (OPEN), but nothing arrives. Servers use protocol pings, as in Step 1. A browser page cannot send protocol pings, so clients add a small application heartbeat: send {"type":"ping"} every 20 to 30 seconds, and if no pong comes back in time, close the socket and reconnect.
Live coding: an accessible live score page
This example uses a simulation. FakeScoreSocket is a stand-in written for this lesson. It has the same open, message and close events, readyState, send() and close() as a real WebSocket, but the balls come from Math.random(). Replace new FakeScoreSocket(...) with new WebSocket(...) and the client code works against a real server.
Step 1: the status line has role="status", so screen readers announce "Live" or "Connection lost" politely.
Step 2: the score itself is not a live region. Announcing every dot ball would talk over everything else. Only fours, sixes and wickets go into the aria-live="polite" list.
Step 3: the client uses backoff with jitter and a heartbeat (every 2 seconds here, so you can see it quickly).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Live score (simulated feed)</title>
<style>
body { font-family: system-ui, sans-serif; max-inline-size: 32rem; margin: 1rem auto; padding: 0 1rem; }
.score { font-size: 2rem; font-weight: bold; margin: 0.5rem 0; }
#status { padding: 4px 8px; border-radius: 6px; background: #eef2f7; }
#status.live { background: #e3f6e8; }
</style>
</head>
<body>
<h1>Jaipur Royals vs Kochi Tuskers</h1>
<p id="status" role="status">Connecting...</p>
<p class="score"><span id="score">0/0</span> <small id="over"></small></p>
<button type="button" id="drop">Simulate a silent network drop</button>
<h2>Big moments</h2>
<ul id="feed" aria-live="polite"></ul>
<script>
// ---- SIMULATION: a fake server that behaves like a WebSocket ----
class FakeScoreSocket extends EventTarget {
static offlineUntil = 0;
static score = { runs: 142, wickets: 3, ball: 102 };
readyState = 0; // CONNECTING
#timer;
constructor(url) {
super();
setTimeout(() => {
if (Date.now() < FakeScoreSocket.offlineUntil) return this.#end(1006); // no network
this.readyState = 1; // OPEN
this.dispatchEvent(new Event("open"));
this.#push({ type: "snapshot", ...FakeScoreSocket.score }); // full state first
this.#timer = setInterval(() => this.#nextBall(), 1500);
}, 400);
}
send(text) {
if (this.readyState !== 1) throw new DOMException("Not open", "InvalidStateError");
if (JSON.parse(text).type === "ping") this.#push({ type: "pong" });
}
close(code = 1000) { this.#end(code); }
#push(msg) {
if (Date.now() < FakeScoreSocket.offlineUntil) return; // silent drop: nothing arrives
this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(msg) }));
}
#nextBall() {
const s = FakeScoreSocket.score;
const options = s.wickets < 9 ? ["0", "1", "1", "2", "4", "6", "W"] : ["0", "1", "4"];
const result = options[Math.floor(Math.random() * options.length)];
s.ball++;
if (result === "W") s.wickets++; else s.runs += Number(result);
this.#push({ type: "ball", result, ...s });
}
#end(code) {
clearInterval(this.#timer);
this.readyState = 3; // CLOSED
this.dispatchEvent(new CloseEvent("close", { code, wasClean: code !== 1006 }));
}
}
// ---- CLIENT: the same code works with a real WebSocket ----
const statusEl = document.querySelector("#status");
let attempt = 0;
let heartbeat;
function setStatus(text, live = false) {
statusEl.textContent = text;
statusEl.classList.toggle("live", live);
}
function show(s) {
document.querySelector("#score").textContent = `${s.runs}/${s.wickets}`;
document.querySelector("#over").textContent = `(${Math.floor(s.ball / 6)}.${s.ball % 6} overs)`;
}
function announce(text) {
const li = document.createElement("li");
li.textContent = text; // never innerHTML for data from the network
document.querySelector("#feed").prepend(li);
}
function connect() {
const socket = new FakeScoreSocket("wss://scores.example.in/match/77");
let lastPong = Date.now();
socket.addEventListener("open", () => {
attempt = 0;
setStatus("Live", true);
heartbeat = setInterval(() => {
if (Date.now() - lastPong > 5000) return socket.close(4000); // no pong: the line is dead
socket.send(JSON.stringify({ type: "ping" }));
}, 2000);
});
socket.addEventListener("message", (event) => {
let msg;
try { msg = JSON.parse(event.data); } catch { return; }
if (msg.type === "pong") lastPong = Date.now();
if (msg.type === "snapshot" || msg.type === "ball") show(msg);
const big = { 4: "FOUR", 6: "SIX", W: "WICKET" }[msg.result];
if (big) announce(`${big}! ${msg.runs}/${msg.wickets}`);
});
socket.addEventListener("close", (event) => {
clearInterval(heartbeat);
if (event.code === 1000) return setStatus("Disconnected");
const delay = Math.min(1000 * 2 ** attempt, 15000) * (0.5 + Math.random() / 2); // backoff + jitter
attempt++;
setStatus(`Connection lost (code ${event.code}). Retrying in ${(delay / 1000).toFixed(1)} s, attempt ${attempt}.`);
setTimeout(connect, delay);
});
}
document.querySelector("#drop").addEventListener("click", () => {
FakeScoreSocket.offlineUntil = Date.now() + 8000; // 8 seconds with no network
});
connect();
</script>
</body>
</html>Watch the score for a few balls, then press the drop button. Nothing arrives, yet nothing looks broken. After about five seconds the heartbeat notices the missing pongs and closes with code 4000. Codes 4000 to 4999 are free for apps to use. In one test run, the status line went: "Live", then "Retrying in 0.6 s, attempt 1", then "attempt 2" and "attempt 3" with code 1006 while the network was still down, then "Live" again with a fresh snapshot.
Security: wss, origins and logins
- Use
wss://only. It is WebSocket over TLS, likehttps://. A page onhttps://cannot openws://anyway: browsers block it as mixed content. - Check
Originon the server. Browsers send cookies with the handshake. Without an origin check, any website can open a socket to your server as your logged-in user. This attack is called cross-site WebSocket hijacking. Step 1 refuses unknown origins. - Authenticate the connection. The browser
WebSocketconstructor cannot set anAuthorizationheader. Use a session cookie together with the origin check. Or fetch a short-lived, single-use ticket over HTTPS and send it in the first message. Avoid long-lived tokens in the URL: URLs end up in server logs. - Distrust every message. Parse inside
try, checktypeand sizes (maxPayloadin Step 1), limit how fast one client may send, and show text withtextContent.
Common mistakes
- Reconnecting at fixed times. Use backoff with jitter.
- Trusting
readyState === 1as proof of life. Only a heartbeat proves messages still flow. - Skipping the origin check because "we use cookies". Cookies are exactly why you need it.
- Making the whole scoreboard an
aria-liveregion. Announce only important changes. - Not sending a snapshot after reconnect. The user missed updates while offline.
Interview questions
1. How does a WebSocket connection start?
With an HTTP GET request carrying Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Version: 13 and a random Sec-WebSocket-Key. The server answers 101 Switching Protocols with a Sec-WebSocket-Accept value derived from the key. After that, the TCP connection carries WebSocket frames in both directions.
2. What is cross-site WebSocket hijacking and how do you prevent it?
A malicious page opens a WebSocket to your server, and the browser attaches the victim's cookies. The attacker's page can then read and send messages as the victim. Prevent it by checking the Origin header against an allow-list during the handshake, and by using tokens or tickets instead of relying on cookies alone.
3. Why add jitter to reconnect backoff?
Backoff alone still makes clients that dropped at the same moment retry at the same moments. Jitter randomises each delay, so the reconnects spread out and a recovering server is not flooded.
4. Why do browser apps need an application-level heartbeat?
Browser JavaScript cannot send or see protocol ping and pong frames. A half-dead connection can stay in readyState 1 for a long time. Sending a small ping message and expecting a pong lets the client detect this and reconnect.
5. How do you send authentication with a browser WebSocket?
You cannot set custom headers, so common choices are a session cookie with a strict origin check, or a short-lived ticket fetched over HTTPS and sent in the first message after open. The server should close the connection if the ticket is missing or invalid.
Key points
- The handshake is an HTTP request upgraded with status 101;
Sec-WebSocket-Acceptis a hash of the browser's key. - Node 22 has a WebSocket client but no server; the
wspackage is a common server choice. - Reconnect with exponential backoff, jitter and a fresh snapshot; stop after your own
close(1000). - Use an application heartbeat to catch silent drops; servers can use protocol pings.
- Use
wss://, checkOrigin, authenticate with cookies plus origin checks or short-lived tickets, and validate every message. - Announce only important updates in an
aria-liveregion; keep connection state inrole="status".
Exercise
Add a match chat to the simulated score page. Put a <form> with a text input under the score. On submit, send {"type":"chat","from":"Ananya","text":...}. Teach FakeScoreSocket to echo chat messages back as {"type":"chat",...}, and show them in a <ul> using textContent. If the socket is not open, keep the message in an outbox array, show "You are offline. Your message will be sent when you reconnect.", and send everything in the outbox in the open handler.
Show solution
// In FakeScoreSocket.send(), after the ping check:
const msg = JSON.parse(text);
if (msg.type === "chat") this.#push({ type: "chat", from: msg.from, text: msg.text.slice(0, 200) });
// Client side
const outbox = [];
let current = null; // set current = socket inside connect()
document.querySelector("#chat").addEventListener("submit", (event) => {
event.preventDefault();
const input = document.querySelector("#chat-text");
const text = JSON.stringify({ type: "chat", from: "Ananya", text: input.value });
if (current?.readyState === 1) current.send(text);
else {
outbox.push(text);
setStatus("You are offline. Your message will be sent when you reconnect.");
}
input.value = "";
});
// Inside the "open" listener:
while (outbox.length) socket.send(outbox.shift());
// Inside the "message" listener:
if (msg.type === "chat") {
const li = document.createElement("li");
li.textContent = `${msg.from}: ${msg.text}`;
document.querySelector("#messages").append(li);
}The outbox keeps messages typed during a drop, and the open handler flushes them in order. textContent makes sure a chat message can never inject HTML.
Quick Quiz
1. Which status code does a server send to accept a WebSocket upgrade?
101 tells the browser that the connection now speaks the WebSocket protocol.
2. Why should a WebSocket server check the Origin header?
Without an origin check, a hostile page can hijack the logged-in user's connection.
3. A socket shows readyState 1, but no message has arrived for a minute. What detects a silent drop?
readyState can stay OPEN on a dead line; only a reply proves the connection works.
4. What does jitter add to reconnect logic?
Randomising delays spreads out reconnects after a mass disconnect.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
