Real-Time Apps in Node.js: WebSockets, Socket.IO and SSE
Chat, live dashboards, notifications, collaborative editing, and AI token streaming all need the server to push data to clients. Node.js's event-driven model is ideal for holding many open connections.
Option 1: Server-Sent Events (SSE)
One-way, server → client, over plain HTTP:
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
const timer = setInterval(() => res.write(`data: ${JSON.stringify({ time: Date.now() })}\n\n`), 1000);
req.on('close', () => clearInterval(timer));
});
Best for: notifications, live feeds, AI response streaming.
Option 2: WebSockets (ws)
Two-way, low-latency:
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (socket) => {
socket.on('message', (msg) => {
wss.clients.forEach((client) => client.send(msg.toString()));
});
});
Best for: chat, games, collaborative tools.
Option 3: Socket.IO
Adds rooms, automatic reconnection, acknowledgements, and fallbacks on top of WebSockets:
io.on('connection', (socket) => {
socket.join(`ticket:${socket.handshake.query.ticketId}`);
socket.on('comment', (c) => io.to(`ticket:${c.ticketId}`).emit('comment', c));
});
Scaling
With multiple Node instances, clients connect to different servers. Use a Redis adapter (Socket.IO) or pub/sub to broadcast across instances, and configure sticky sessions where required.
Security
- Authenticate on connection (token in handshake)
- Validate every incoming message
- Rate-limit messages per connection
Use SSE when the server talks, WebSockets when both sides talk.