Full answer
Basics
- WebSocket starts as an HTTP request with Upgrade: websocket, then both sides send messages whenever they want. It suits chat, live dashboards and collaborative tools. For one-way server updates, Server-Sent Events are simpler.
- ws is the common Node library. new WebSocketServer({ port }) or { server } to share an HTTP server. wss.on('connection', (socket, request) => ...).
- Messages arrive as Buffers (isBinary tells the type). Convert text with data.toString() and parse JSON inside try/catch.
- Close codes: 1000 normal, 1001 going away, 1008 policy violation, 1009 message too big, 1011 server error. Set maxPayload to limit the message size.
Broadcast
- Loop over wss.clients. Check client.readyState === WebSocket.OPEN before send. Skip the sender when needed.
Heartbeat
- TCP can stay half-open after a phone loses the network or a proxy drops the connection. The server may never see 'close'.
- Every 30 seconds: for each client, if isAlive is false then terminate(). Otherwise set isAlive to false and call ping(). On 'pong', set isAlive back to true.
- Browsers answer ping frames automatically. The browser API cannot send them, so application-level pings are needed in some cases.
- Proxies often close idle connections after 60 seconds, so the heartbeat also keeps them open.
Also remember: authenticate during the upgrade, validate every message, rate limit per connection, handle 'error' events, clean up per-connection state on close, and expect clients to reconnect (use exponential backoff on the client).
const { WebSocketServer, WebSocket } = require('ws');
const { once } = require('node:events');
const { setTimeout: sleep } = require('node:timers/promises');
async function main() {
const wss = new WebSocketServer({ port: 0, maxPayload: 1024 });
await once(wss, 'listening');
const url = 'ws://127.0.0.1:' + wss.address().port;
wss.on('connection', (socket) => {
socket.isAlive = true;
socket.on('error', () => {}); // always handle errors, for example a message above maxPayload
socket.on('pong', () => { socket.isAlive = true; });
socket.on('message', (data, isBinary) => {
const text = data.toString();
for (const client of wss.clients) {
if (client !== socket && client.readyState === WebSocket.OPEN) client.send(text); // broadcast to everyone else
}
socket.send('ack: ' + text);
});
});
// Heartbeat: one round of the loop that a real server runs every 30 seconds.
const heartbeat = () => {
let terminated = 0;
for (const client of wss.clients) {
if (!client.isAlive) { client.terminate(); terminated++; continue; }
client.isAlive = false;
client.ping();
}
return terminated;
};
const connect = async () => {
const client = new WebSocket(url);
client.inbox = [];
client.on('message', (data) => client.inbox.push(data.toString()));
await once(client, 'open');
return client;
};
const a = await connect();
const b = await connect();
// A client that never answers pings, like a phone that lost its network.
const silent = new WebSocket(url, { autoPong: false });
silent.on('error', () => {});
await once(silent, 'open');
await sleep(20);
a.send('hello from A');
await sleep(50);
console.log('A inbox:', JSON.stringify(a.inbox));
console.log('B inbox:', JSON.stringify(b.inbox));
console.log('connected clients:', wss.clients.size);
console.log('first heartbeat terminated:', heartbeat()); // everyone is marked and pinged
await sleep(50); // a and b answer with pong, silent does not
const terminated = heartbeat();
await sleep(30);
console.log('second heartbeat terminated:', terminated, '| clients left:', wss.clients.size);
// Oversized message: the server closes the connection with code 1009.
const c = await connect();
c.on('error', () => {});
const closed = once(c, 'close');
c.send('x'.repeat(5000));
const [code] = await closed;
console.log('oversized message closes the connection with code', code);
for (const client of wss.clients) client.terminate();
wss.close();
}
main();Three clients connect and one never answers pings. One message is broadcast, two heartbeat rounds remove the silent client, and an oversized message is rejected with close code 1009. Install first with npm install ws (run here with ws 8.23.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): A inbox: ["ack: hello from A"] B inbox: ["hello from A"] connected clients: 3 first heartbeat terminated: 0 second heartbeat terminated: 1 | clients left: 2 oversized message closes the connection with code 1009
Key points
- WebSocket is a persistent two-way connection after an HTTP upgrade.
- Check readyState before sending when broadcasting.
- Ping and pong detect dead connections.
- Limit payload size and validate messages.
- Clients must reconnect with backoff.
Common mistakes
- Calling send() without checking readyState.
- Relying on the 'close' event alone to detect dead clients.
- No payload limit, so one client can send huge messages.
- Keeping per-connection data after the socket closed.
- No reconnect logic on the client.
Follow-ups
- How does the browser WebSocket API differ from ws on the server?
- When would you choose Server-Sent Events over WebSocket?
- How do you authenticate a WebSocket connection?
Tips
- Say 'HTTP upgrade' in the first sentence.
- Describe the isAlive pattern.
- Mention close code 1009.