HTML Server-Sent Events (SSE)
SSE (Server-Sent Events) allow servers to push real-time updates to the browser over a single HTTP connection. Unlike WebSockets, it is one-way (server → client). Unlike normal HTTP requests, where the browser repeatedly asks for new data, with SSE the server automatically sends updates whenever new data is available.
Use Cases:
- News websites (live headlines)
- Stock/crypto updates (real-time prices)
- Weather alerts
- Social media notifications
- Live sports scores
How SSE Works (Client + Server)
SSE is based on a one-way communication model:
- Client (browser) → Creates a connection using
EventSource
. - Server → Sends events/messages in
text/event-stream
format.
👉 Think of it like radio broadcasting: once connected, you keep receiving updates automaticall
Client-Side (Browser) Code
You use the EventSource API in JavaScript to listen for events.
<!DOCTYPE html>
<html>
<head>
<title>Server-Sent Events Example</title>
</head>
<body>
<h2>🔴 Live Updates from Server</h2>
<div id="updates"></div>
<script>
// Create connection to server
const eventSource = new EventSource("server.php");
// When a new message arrives
eventSource.onmessage = function(event) {
document.getElementById("updates").innerHTML += "<p>" + event.data + "</p>";
};
// When connection is established
eventSource.onopen = function() {
console.log("Connected to server ✅");
};
// When an error occurs
eventSource.onerror = function() {
console.log("Error ❌ or lost connection");
};
</script>
</body>
</html>
Server-Side Code Examples
(A) SSE with PHP
<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Connection: keep-alive");
// Send updates every 3 seconds
while (true) {
echo "data: Current server time: " . date("h:i:s") . "\n\n";
ob_flush();
flush();
sleep(3);
}
?>
Content-Type: text/event-stream
→ tells browser this is SSE data.- Each message starts with
data:
and ends with two newlines. flush()
ensures the data is sent immediately.
(B) SSE with Node.js (Express)
const express = require("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");
// Send an event every 3 seconds
setInterval(() => {
res.write(`data: Server time: ${new Date().toLocaleTimeString()}\n\n`);
}, 3000);
});
app.listen(3000, () => console.log("SSE server running on http://localhost:3000"));
/events
→ SSE endpoint.res.write("data: ... \\n\\n")
→ sends messages to the client.- Client connects via
new EventSource("<http://localhost:3000/events>");
.
Client connects using:
const eventSource = new EventSource("http://localhost:3000/events");
Custom Events in SSE
You can send custom events instead of only onmessage
.
Server (PHP Example):
echo "event: priceUpdate\n";
echo "data: Bitcoin Price: $40,000\n\n";
flush();
Client:
eventSource.addEventListener("priceUpdate", function(event) {
console.log("Custom Event → " + event.data);
});
Closing an SSE Connection
When updates are no longer needed:
eventSource.close();
console.log("Connection closed ❌");
Error Handling in SSE
SSE automatically tries to reconnect if the connection is lost, but you should still handle errors.
eventSource.onerror = function() {
console.log("⚠️ Lost connection, retrying...");
};
Advantages & Limitations
Advantages:
- Simple & lightweight compared to WebSockets.
- Built-in auto-reconnect.
- Works over normal HTTP/HTTPS.
Limitations:
- One-way only (server → client).
- Cannot send binary data (only text).
- Not supported in Internet Explorer.
Real-World Applications of SSE
- News apps → Live headlines
- Finance → Real-time stock/crypto updates
- Social media → Notifications
- Sports → Live scores
- Weather → Instant weather alerts