Real-time with WebSockets
Overview
HTTP is request–response: the client asks, the server answers. But some features need the server to speak first — a new chat message, a live score, a notification, another user’s cursor in a shared document.
You could make the client ask “anything new?” every couple of seconds (polling), but that’s slow and wasteful. A WebSocket keeps one connection open, and either side can send a message at any moment.
How the connection starts
A WebSocket begins life as an ordinary HTTP request with an Upgrade: websocket header. The server replies 101 Switching Protocols, and from then on the same TCP connection carries WebSocket frames in both directions. Because it starts as HTTP, it can share your existing server and port, and works through most proxies and load balancers.
Browsers have a built-in WebSocket class (Node has it too, for clients):
const socket = new WebSocket('wss://api.academy.com/ws');
socket.addEventListener('open', () => socket.send(JSON.stringify({ type: 'join', room: 'js' })));
socket.addEventListener('message', (event) => console.log(JSON.parse(event.data)));Use wss:// (WebSocket over TLS) in production, just as you use https://.
A WebSocket server with ws
ws is the most widely used WebSocket library for Node — small, fast and close to the protocol.
npm install wsimport http from 'node:http';
import express from 'express';
import { WebSocketServer, WebSocket } from 'ws';
const app = express();
const server = http.createServer(app); // share one server for HTTP and WebSockets
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: 16 * 1024 });
wss.on('connection', (socket, req) => {
socket.send(JSON.stringify({ type: 'welcome' }));
socket.on('message', (data) => {
// data is a Buffer; most apps exchange JSON
console.log('received', data.toString());
});
socket.on('close', () => console.log('client left'));
socket.on('error', (err) => console.error('socket error', err));
});
server.listen(3000);Broadcasting
wss.clients is a Set of every connected socket:
function broadcast(message, filter = () => true) {
const data = JSON.stringify(message);
for (const client of wss.clients) {
if (client.readyState === WebSocket.OPEN && filter(client)) client.send(data);
}
}
broadcast({ type: 'announcement', text: 'Live class starts in 5 minutes' });Attach your own properties to sockets (socket.userId, socket.room) to target groups.
Design a message protocol
WebSockets just move strings and bytes; you decide what they mean. A simple, common convention is JSON messages with a type:
{ "type": "join", "room": "course-42" }
{ "type": "message", "text": "Has anyone finished the streams exercise?" }
{ "type": "typing", "isTyping": true }Validate every incoming message as carefully as an HTTP body — a WebSocket is just another way for untrusted data to reach your server. Parse inside try, check types (a Zod schema works well), and ignore or reject anything unexpected. maxPayload stops giant messages.
Authentication
Authenticate when the connection is established, not per message. Browsers can’t set custom headers on WebSocket requests, so use a cookie (sessions) or a short-lived token in the URL:
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', async (req, socket, head) => {
try {
const user = await authenticateUpgrade(req); // check the session cookie or ?token=
wss.handleUpgrade(req, socket, head, (ws) => {
ws.user = user;
wss.emit('connection', ws, req);
});
} catch {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
}
});Also check the Origin header during the upgrade, so other websites can’t open connections using your users’ cookies.
Detecting dead connections
A phone that loses signal doesn’t always close its connection properly; the server may think it’s still there forever. Heartbeats detect this: the server pings regularly, and drops clients that don’t answer.
wss.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
});
const interval = setInterval(() => {
for (const ws of wss.clients) {
if (!ws.isAlive) { ws.terminate(); continue; }
ws.isAlive = false;
ws.ping();
}
}, 30_000);
wss.on('close', () => clearInterval(interval));On the client side, reconnect automatically with backoff when the connection drops.
Scaling across servers
Each Node process only knows about its own connections. With two servers, a message sent by a user on server A won’t reach users connected to server B.
The usual fix is Redis pub/sub: every server subscribes to channels, and publishes messages there instead of broadcasting directly:
import Redis from 'ioredis';
const pub = new Redis(process.env.REDIS_URL);
const sub = new Redis(process.env.REDIS_URL); // a subscribing connection can't run other commands
await sub.subscribe('chat');
sub.on('message', (channel, raw) => {
const msg = JSON.parse(raw);
broadcast(msg, (client) => client.room === msg.room);
});
// when a client sends a message:
pub.publish('chat', JSON.stringify({ type: 'message', room, text }));Alternatives
- Socket.IO — a popular library built on WebSockets that adds rooms, automatic reconnection, acknowledgements and fallbacks. Its clients only talk to Socket.IO servers.
- Server-Sent Events (SSE) — one-way server→client streaming over plain HTTP (
Content-Type: text/event-stream) with automatic reconnection in browsers. Perfect for notifications, progress updates and streaming AI responses. - Managed services — Pusher, Ably, Supabase Realtime and others handle the connections for you.
Choose the simplest tool: SSE if only the server talks, WebSockets when both sides do, and polling when updates are rare and a few seconds’ delay is fine.
A chat room server
Using ws, attach a WebSocket server to an HTTP server at path /ws. Clients send { "type": "join", "room": "js" } or { "type": "message", "text": "…" }. Broadcast each message to everyone in the same room as { type: 'message', room, text, at }. Ignore invalid JSON and messages over 1 KB.
import http from 'node:http';
import { WebSocketServer } from 'ws';
const server = http.createServer();
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: 1024 });
// your code here
server.listen(3000);import http from 'node:http';
import { WebSocketServer, WebSocket } from 'ws';
const server = http.createServer();
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: 1024 });
wss.on('connection', (socket) => {
socket.room = null;
socket.on('message', (raw) => {
let msg;
try { msg = JSON.parse(raw); } catch { return; }
if (msg.type === 'join' && typeof msg.room === 'string') {
socket.room = msg.room.slice(0, 50);
} else if (msg.type === 'message' && socket.room && typeof msg.text === 'string') {
const out = JSON.stringify({ type: 'message', room: socket.room, text: msg.text, at: Date.now() });
for (const client of wss.clients) {
if (client.room === socket.room && client.readyState === WebSocket.OPEN) client.send(out);
}
}
});
});
server.listen(3000);Summary
- A WebSocket is a long-lived, two-way connection: the server can send data whenever it likes.
- It starts as an HTTP request that is upgraded, so it can share your HTTP server and port.
- Authenticate during the upgrade, validate every incoming message, and cap message size.
- Use ping/pong heartbeats to detect dead connections.
- With several servers, relay messages through Redis pub/sub so every client gets them.