WebSockets vs Server-Sent Events for a notification feature
asked 2 months ago201 viewsen
I want to push notifications to users in real time (new answer, new message). Should I use WebSockets or SSE?
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
1 Answer
For server → client notifications, SSE is usually the simpler and better choice:
- It's plain HTTP: it works through proxies and CDNs, and cookie auth works as-is. - The browser's EventSource reconnects automatically, with Last-Event-ID resume. - It's one-way, which is exactly what notifications are. The client sends actions through normal POST requests.
app.get('/events', (req, res) => {
res.set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
const send = (evt) => res.write(`id: ${evt.id}\ndata: ${JSON.stringify(evt)}\n\n`);
const unsub = bus.subscribe(req.user.id, send);
req.on('close', unsub);
});
Pick WebSockets when you need frequent bidirectional, low-latency traffic: multiplayer games, collaborative editing, live cursors.
With either one and multiple server instances, use a pub/sub layer (Redis, Postgres LISTEN/NOTIFY) so an event reaches the instance holding the user's connection.
Sign in to tell others whether this worked.
Sign in and verify your email to post an answer.