πΉ 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:
- Client opens a connection using
EventSource
. - Server responds with
Content-Type: text/event-stream
. - Server pushes messages in a special format.
- Browser delivers events to your JavaScript app.
Client (EventSource) <--- HTTP Stream ---> Server
πΉ 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"));
π» 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>
);
}
πΉ Sending Custom Events
SSE isnβt limited to message
events. You can send custom event types:
Server:
event: priceUpdate
data: 123.45
Client:
eventSource.addEventListener("priceUpdate", (e) => {
console.log("Price update:", e.data);
});
πΉ Handling Errors & Reconnection
- By default,
EventSource
auto-reconnects if the connection drops. - You can control retry interval by sending:
retry: 5000
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.
βοΈ Written by [Srinivasa Reddy Thumu]
π Letβs connect on LinkedIn
Top comments (0)