HTML Server-Sent Events (SSE) allow web pages to receive automatic, real-time push updates from a web server over a single persistent HTTP connection using the native EventSource JavaScript API.
Unlike WebSockets which support two-way communication, SSE provides efficient one-way streaming from server to client:
// Connect to real-time server stream endpoint
const eventSource = new EventSource("/api/live-stream");
// Listen for incoming server messages
eventSource.onmessage = (event) => {
console.log("New Server Data:", event.data);
};
// Handle connection errors
eventSource.onerror = () => {
console.log("Connection lost, reconnecting...");
};
Key SSE features:
eventSource.addEventListener('news', ...)).flowchart TD
A["Real-Time Streaming Choice"] --> B["Server-Sent Events (SSE)"]
A --> C["WebSockets"]
B --> B1["One-Way (Server to Client) + Auto-Reconnect + Standard HTTP"]
C --> C1["Two-Way (Bidirectional) + Custom TCP Socket Connection"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Server-Sent Events Example</title>
</head>
<body style="font-family: system-ui, sans-serif; background-color: #0f172a; color: #f8fafc; padding: 2rem;">
<h2>Live Stock Price Ticker (SSE)</h2>
<div style="background-color: #1e293b; padding: 1.5rem; border-radius: 8px; max-width: 400px;">
<p>Market Status: <span style="color: #34d399; font-weight: bold;">CONNECTED</span></p>
<div id="ticker" style="font-size: 1.25rem; color: #38bdf8; font-weight: bold;">Waiting for updates...</div>
</div>
<script>
const ticker = document.getElementById("ticker");
// Simulate SSE event stream handling
if (typeof(EventSource) !== "undefined") {
// Demo stream connection point
const source = new EventSource("https://express-eventsource.example.com/stream");
source.onmessage = (event) => {
ticker.textContent = "Price: $" + event.data;
};
// Demo fallback update simulation
setTimeout(() => {
ticker.textContent = "AAPL: $235.50 (Live Stream Data)";
}, 1000);
} else {
ticker.textContent = "SSE not supported in this browser.";
}
</script>
</body>
</html>
eventSource.close() when navigating away to free up server connection slots.Content-Type: text/event-stream on server endpoints: Backend API responses must return the text/event-stream HTTP header.Create an EventSource instance connecting to /stream and attach an onmessage event listener!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.