WebSockets vs Server-Sent Events for a notification feature

posée 2 months ago201 vuesen

6

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

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 2 months ago

1 réponse

8
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 2 months ago

Sign in and verify your email to post an answer.