Skip to content
Brijesh Yadav

← All posts

Server-Sent Events (SSE) for Live Analytics Feeds

Aug 15, 2025 · 5 min read

Real-time analytics are essential for modern web applications, especially dashboards and monitoring tools. Server-Sent Events (SSE) provide a simple, robust way to push live updates from the server to the browser, making them ideal for streaming analytics data to the UI without the overhead of WebSockets.

What are Server-Sent Events?

Server-Sent Events (SSE) is a browser API that allows servers to push text-based event data to clients over HTTP. Unlike WebSockets, SSE is unidirectional (server to client) and uses a simple, native event stream format.

  • Protocol: Standard HTTP / HTTPS
  • Direction: Server → Client (Unidirectional)
  • Format: text/event-stream

How SSE Works

  1. The client (browser) opens a persistent connection to the server using JavaScript's native EventSource API.
  2. The server responds with an HTTP stream of events, each formatted as text separated by double newlines.
  3. The browser receives and processes events in real time, firing event listeners automatically.
SSE Communication Flow
  ┌─────────────┐                                ┌─────────────┐
  │   Browser   │ ─── 1. HTTP GET /events ─────▶ │ Server API  │
  │ (Client UI) │ ◀── 2. text/event-stream ───── │  (Node.js)  │
  └─────────────┘                                └─────────────┘
         │                                              │
         │ ◀─── 3. data: {"users": 42} ─────────────────┤ (Keep-Alive Stream)
         │ ◀─── 4. data: {"users": 45} ─────────────────┤
          

Example: Live Analytics Feed

Backend (Node.js Example)

const http = require("http");

http
  .createServer((req, res) => {
    if (req.url === "/events") {
      res.writeHead(200, {
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
        Connection: "keep-alive",
      });
      setInterval(() => {
        const data = JSON.stringify({
          users: Math.floor(Math.random() * 100),
          sales: Math.floor(Math.random() * 50),
        });
        res.write(`data: ${data}\n\n`);
      }, 2000);
    } else {
      res.writeHead(404);
      res.end();
    }
  })
  .listen(3000);

Frontend (HTML + JS)

<div id="analytics"></div>
<script>
  const analyticsDiv = document.getElementById("analytics");
  const source = new EventSource("/events");
  source.onmessage = function (event) {
    const data = JSON.parse(event.data);
    analyticsDiv.innerHTML = `Users: ${data.users}, Sales: ${data.sales}`;
  };
</script>

Use Cases

  • Real-time dashboards — live metrics, CPU/memory stats, active user counters.
  • Live notifications — status alerts, build pipeline updates, system health triggers.
  • Monitoring systems — log tailing and telemetry feeds.
  • Stock tickers — streaming price updates where client-to-server messages aren't needed.

Best Practices

  • Use SSE for simple, unidirectional data streams where WebSockets would be overkill.
  • For bidirectional communication (e.g., chat apps, interactive games), consider WebSockets.
  • Handle reconnections gracefully in the client using the native reconnection capabilities of EventSource.
  • Secure your endpoints with authentication headers or tokens and validate incoming stream data.

Conclusion

SSE is a powerful, lightweight tool for streaming live analytics to your UI with minimal setup. It works seamlessly over standard HTTP, bypasses firewall issues often encountered with WebSockets, and provides native browser reconnect handling out of the box.

← All posts · Projects