Server-Sent Events (SSE) allow a web server to push live updates straight to the browser over a single persistent HTTP connection. Unlike polling fetch() every five seconds, SSE delivers real-time stock tickers, build logs, or notification feeds as soon as events occur on the backend.
On the frontend, instantiate new EventSource('/api/stream') and attach an onmessage listener. The browser keeps the connection open, parses incoming data: lines, and automatically reconnects if the network drops briefly.
On the server side, the endpoint must return Content-Type: text/event-stream and flush messages formatted as `data: payload
`.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML SSE Demo</title>
</head>
<body style="font-family: system-ui, sans-serif; padding: 20px;">
<h2>Live Event Stream</h2>
<ul id="feed"></ul>
<script>
const feed = document.getElementById('feed');
if ('EventSource' in window) {
const source = new EventSource('/api/live-events');
source.onmessage = (event) => {
const li = document.createElement('li');
li.textContent = event.data;
feed.appendChild(li);
};
source.addEventListener('status', (event) => {
console.log('Named status event:', event.data);
});
source.onerror = () => {
console.warn('Stream interrupted; browser will attempt reconnect.');
};
}
</script>
</body>
</html>
SSE sends data in one direction—from server to browser—over standard HTTP/HTTPS, making it simpler to proxy, authenticate, and auto-reconnect. Choose WebSockets only when you need rapid two-way messaging like multiplayer games or real-time collaborative whiteboards.
on the server**: Browsers buffer incoming SSE lines until they receive
` marking the end of an event.
source.close() when unmounting components so stale listeners do not accumulate.Yes. Automatic reconnection (typically after ~3 seconds) and Last-Event-ID tracking are built directly into the browser EventSource specification.
Yes. Serialize JSON onto a single `data: {"price":42}
line on the server and runJSON.parse(event.data)in youronmessage` handler.
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.