Back to results for “Communication”
Node.js › HTTP & Web Servers

How would you implement Server-Sent Events (SSE) in Node.js to push real-time updates to a browser client over a single long-lived HTTP connection?

Advanced

Answer

SSE keeps a single HTTP response open indefinitely, with the server writing formatted text events to it over time (rather than closing the connection after one response) -- the client uses the browser's built-in EventSource API to receive these events as they arrive, providing a simpler one-directional (server-to-client only) alternative to WebSockets for use cases like live notifications or progress updates that don't need the client to send messages back over the same connection.
app.get('/events', (req, res) => {
  res.set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
  const interval = setInterval(() => {
    res.write(`data: ${JSON.stringify({ time: Date.now() })}\n\n`);
  }, 1000);
  req.on('close', () => clearInterval(interval));
});

// Client: const events = new EventSource('/events');
// events.onmessage = (e) => console.log(JSON.parse(e.data));
Real-world example A live-dashboard application uses Server-Sent Events to push updated metrics to connected browsers every few seconds, choosing SSE over the added complexity of WebSockets since the dashboard only ever needs to receive data, never send anything back to the server over that same connection.

Common follow-ups: Why would WebSockets be a better choice than SSE if the client also needed to send frequent messages back to the server?;How do you handle cleaning up server-side resources when a client's SSE connection is closed or the browser tab is closed?