WebSockets and Socket.IO
Real-time messaging in Node with ws and Socket.IO. Rooms, heartbeats, connect-time auth, and why scaling past one process needs an adapter.
The http module and building a serverEvents and EventEmitter
WebSockets and Socket.IO
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A WebSocket starts as an HTTP request that upgrades to a persistent, full-duplex connection, so the server can push messages without the client asking. In Node the `ws` library attaches to an `http` server.
- `ws` is a thin, fast implementation of the protocol: you write your own message format, rooms and reconnection. Socket.IO is a higher-level library with named events, acknowledgements, rooms, automatic reconnection and fallbacks, and it has its own protocol, so a Socket.IO server only talks to Socket.IO clients.
- Detect dead connections with heartbeats: ping every client on an interval, mark it not alive, and terminate any that did not pong before the next round. TCP alone can take minutes to notice a vanished client.
- Authenticate during the handshake (a token in the connection's auth data, or a cookie) and set `maxPayload` so a single frame cannot exhaust memory.
- Connection state lives in one process's memory. With several servers, clients in the same room can be on different machines, so you need a pub/sub backed adapter (Socket.IO's Redis adapter, for example) and sticky routing for HTTP fallback transports.
Why a persistent connection
HTTP is request and response: the client asks, the server answers, the exchange is over. To get live updates, a page would have to ask again and again. WebSockets flip that. A client sends a normal HTTP request with an Upgrade: websocket header, the server agrees, and the same TCP connection becomes a two-way message channel that stays open. Either side can send at any moment. That fits chat, live prices, collaborative editing and games. For the trade-offs against server-sent events and long polling, see real-time features in practice and the API contract view.
The ws library
Node has no built-in WebSocket server, and ws is the standard one. It attaches to an existing http server, so it shares a port with your HTTP routes:
import { createServer } from 'node:http';
import { WebSocketServer, WebSocket } from 'ws';
const server = createServer((req, res) => res.end('http ok'));
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: 64 * 1024 });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
for (const peer of wss.clients) {
if (peer !== ws && peer.readyState === WebSocket.OPEN) peer.send(data.toString());
}
});
ws.on('error', (e) => console.error('ws error', e.message));
});
server.listen(3000);
A WebSocketServer is an event emitter, so everything from events and EventEmitter applies, including the need for an error listener. ws gives you frames and nothing more: you decide the message format (usually JSON with a type field), how rooms work, and what happens on reconnect. A hand-built room is a Map of room name to a Set of sockets, cleaned up on close. I ran a version with join and say messages: two clients joined r1, one said hi, and the other received it. Sending invalid JSON got back a bad json error message, and a 70 KiB frame against maxPayload 64 KiB closed the socket with code 1009 (message too big).
Heartbeats
A closed laptop lid or a dropped mobile connection sends no close frame. The server’s socket looks open until TCP gives up, which can take minutes. The standard fix is an application-level heartbeat:
wss.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
});
const beat = setInterval(() => {
for (const ws of wss.clients) {
if (!ws.isAlive) { ws.terminate(); continue; }
ws.isAlive = false;
ws.ping();
}
}, 30_000);
wss.on('close', () => clearInterval(beat));
Browsers answer pings with pongs automatically. Each round, a client that did not pong since the last round is dropped. In my test, with a 40 ms interval, a client I froze so it could not read the ping was terminated and a healthy one stayed. Clean up per-connection state in the close handler, or you leak memory for every client that vanished.
Socket.IO
Socket.IO sits on top of WebSocket (with a long-polling fallback) and adds a protocol of its own:
import { Server } from 'socket.io';
const io = new Server(httpServer, { cors: { origin: ['https://app.example.com'] } });
io.use((socket, next) =>
socket.handshake.auth.token === 'ok' ? next() : next(new Error('unauthorized')));
io.on('connection', (socket) => {
socket.on('join', (room, ack) => { socket.join(room); ack({ joined: room }); });
socket.on('say', ({ room, text }) => socket.to(room).emit('say', { from: socket.id.slice(0, 4), text }));
});
You get named events instead of parsing JSON by hand, acknowledgement callbacks, rooms (socket.join, socket.to(room).emit), middleware at connect time, and reconnection on the client. In my run with socket.io 4.8, a client in r1 received a message from another in r1, a third client outside the room did not, and a client sending the wrong token was rejected with unauthorized. The cost is that a Socket.IO server speaks only to Socket.IO clients; a plain new WebSocket(...) cannot talk to it.
Scaling is the catch
All of the above lives in one process’s memory: the socket list, the rooms, the heartbeats. Add a second process (see cluster) or a second machine and room membership splits. A message to room r1 reaches only the sockets on the process that handled it. The default adapter reported its class as plain Adapter, the in-memory one. The fix is an adapter that relays broadcasts through shared pub/sub, such as Socket.IO’s Redis adapter, plus sticky sessions at the load balancer if clients may fall back to long polling. With raw ws, you build the same relay yourself. The general constraint is in stateless services and session affinity.
What the video covers
Fireship’s “WebSockets in 100 Seconds & Beyond with Socket.io” (December 2020, 8:31) explains WebSocket fundamentals in about 100 seconds and then builds a small group chat with Socket.IO. It is the quickest honest on-ramp, but it is five years old, and it covers neither the ws library, heartbeats, authentication, nor scaling. Those, and the version details (Socket.IO 4.8 here), come from this page. The video has no caption track, so I could not check anything beyond its title and description. Hussein Nasser’s video in “go deeper” covers the scaling problem with Redis and HAProxy.
Where this fits
WebSockets reuse the http server and event model you already know, and their connection handling is a good test of heartbeats and cleanup. This closes the HTTP group. Next the course moves to data and configuration.
Check yourself
Why use WebSockets instead of polling an endpoint every second?
A polled endpoint costs a full HTTP request per client per interval even when nothing changed, and updates arrive up to one interval late. A WebSocket keeps one connection open and the server sends a message the moment something happens, which is cheaper and lower latency for chat, live dashboards and games.
A client's laptop loses Wi-Fi without closing the socket. How does a `ws` server find out?
Through a heartbeat. The server pings each client on a timer and sets `isAlive = false` before each ping, then sets it back to true on `pong`. A client that stays false by the next round gets `terminate()`d. In a test, a paused client was terminated while a healthy one stayed connected.
When would you pick `ws` over Socket.IO?
When you want the raw protocol, small overhead, or must interoperate with non-Socket.IO clients such as browsers' native `WebSocket` or other languages. Choose Socket.IO when you want rooms, acknowledgements, automatic reconnection and a simple event API without building them yourself.
You run two Node processes behind a load balancer. User A in process 1 sends a message to a room that user B joined on process 2. What happens by default?
B does not receive it. The default Socket.IO adapter keeps rooms in memory per process, so a broadcast only reaches sockets connected to the same process. A Redis (or other pub/sub) adapter relays room messages between processes.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.