How to broadcast messages to all connected WebSocket clients
wss.clients Set, iterating clients, readyState check before send, targeted send vs broadcast, sender exclusion pattern, message fanout, client count metrics
Broadcasting to All Clients
wss.clients is a Set of all currently connected client sockets. Iterate it to broadcast:
function broadcast(wss, message) { const payload = JSON.stringify(message); for (const client of wss.clients) { if (client.readyState === WebSocket.OPEN) { client.send(payload); } } } wss.on('connection', (ws) => { ws.on('message', (data) => { const msg = JSON.parse(data.toString()); // Broadcast to everyone except the sender const payload = JSON.stringify({ type: 'chat', ...msg }); for (const client of wss.clients) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(payload); } } }); });
Always Check readyState Before Sending
A client in wss.clients may be in CLOSING state โ its socket is in the set but calling send() will throw. The readyState === WebSocket.OPEN guard is mandatory in every broadcast loop. Serialize the message once before the loop, not inside it โ JSON.stringify on a large object inside a 10,000-client loop is a performance problem.
Track wss.clients.size in a metrics gauge to monitor connected client count over time.
