WebSockets vs Server-Sent Events for a notification feature

poze 2 months ago199 gadeen

6

I want to push notifications to users in real time (new answer, new message). Should I use WebSockets or SSE?

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 2 months ago

1 Repons

8
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

answered 2 months ago

Sign in and verify your email to post an answer.