DEV Community

Thumu. Srinivas Reddy
Thumu. Srinivas Reddy

Posted on

Server-Sent Events (SSE)

πŸ”Ή Introduction

Have you ever wanted to update your frontend in real-time without complex WebSockets or wasteful polling? That’s where Server-Sent Events (SSE) shine.

SSE is a simple mechanism where the server pushes data to the client over a single, long-lived HTTP connection. It’s lightweight, reliable, and already built into browsers via the EventSource API.


πŸ”Ή Why Use SSE?

Here’s why SSE is awesome:

βœ… Simple – just standard HTTP, no special protocol.
βœ… One-way streaming – perfect when only server β†’ client communication is needed.
βœ… Automatic reconnection – handled by the browser.
βœ… Low overhead – no repeated polling requests.
βœ… Firewall-friendly – works over standard HTTP/HTTPS.

Use cases:

  • Stock price updates πŸ“ˆ
  • Notifications πŸ””
  • Live dashboards πŸ“Š
  • Chat messages πŸ’¬
  • Streaming logs πŸ–₯️

πŸ”Ή How SSE Works

The workflow is straightforward:

  1. Client opens a connection using EventSource.
  2. Server responds with Content-Type: text/event-stream.
  3. Server pushes messages in a special format.
  4. Browser delivers events to your JavaScript app.
Client (EventSource)  <--- HTTP Stream --->  Server
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Basic Example

πŸ–₯️ Server (Node.js + Express)

import express from "express";
const app = express();

app.get("/events", (req, res) => {
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");

  let count = 0;

  // Send a message every 2 seconds
  const interval = setInterval(() => {
    res.write(`data: Hello ${count++} at ${new Date().toISOString()}\n\n`);
  }, 2000);

  // If client closes connection, stop sending
  req.on("close", () => {
    clearInterval(interval);
  });
});

app.listen(3000, () => console.log("SSE server running on http://localhost:3000"));
Enter fullscreen mode Exit fullscreen mode

πŸ’» Client (React Example)

import { useEffect, useState } from "react";

export default function Notifications() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const eventSource = new EventSource("http://localhost:3000/events");

    eventSource.onmessage = (event) => {
      setMessages((prev) => [...prev, event.data]);
    };

    eventSource.onerror = (err) => {
      console.error("SSE error:", err);
      eventSource.close();
    };

    return () => {
      eventSource.close(); // cleanup
    };
  }, []); // βœ… run only once

  return (
    <div>
      <h2>πŸ”” Notifications</h2>
      <ul>
        {messages.map((msg, i) => (
          <li key={i}>{msg}</li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Sending Custom Events

SSE isn’t limited to message events. You can send custom event types:

Server:

event: priceUpdate
data: 123.45
Enter fullscreen mode Exit fullscreen mode

Client:

eventSource.addEventListener("priceUpdate", (e) => {
  console.log("Price update:", e.data);
});
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Handling Errors & Reconnection

  • By default, EventSource auto-reconnects if the connection drops.
  • You can control retry interval by sending:
retry: 5000
Enter fullscreen mode Exit fullscreen mode

This tells the client to reconnect after 5 seconds.

  • Always handle errors gracefully in onerror.

πŸ”Ή SSE vs WebSockets vs Polling

Feature Polling πŸ”„ SSE πŸ“‘ WebSockets πŸ”€
Direction Client β†’ Server only Server β†’ Client only Full duplex
Complexity Low Medium High
Overhead High Low Medium
Browser Support βœ… All βœ… Modern βœ… Modern
Best For Occasional updates Server β†’ client streams Bidirectional chat/games

πŸ”Ή Limitations of SSE

  • Only supports server β†’ client (not bidirectional).
  • Text only (no binary).
  • Browser connection limit (~6 per domain).
  • Not supported in IE (but works in all modern browsers).

πŸ”Ή Conclusion

If you need real-time server β†’ client updates and don’t want the complexity of WebSockets, SSE is the perfect choice. It’s lightweight, browser-native, and great for things like notifications, dashboards, or logs.


SSE Client Server Sample Dialgram


✍️ Written by [Srinivasa Reddy Thumu]
πŸ”— Let’s connect on LinkedIn

Top comments (0)