HTML SSE
HTML Server-Sent Events (SSE): One-Way Live Updates
HTML Server-Sent Events (SSE) let a web server push live updates to the browser over a single, long-lived HTTP connection. Instead of calling fetch() every few seconds to ask whether anything changed, the browser listens and receives each event the moment the server sends it. This lesson covers the EventSource API, the server format, a working example, and the mistakes that most often break a stream.
If you are new to browser APIs, our HTML5 APIs overview is a helpful warm-up.
How Server-Sent Events Work
SSE suits live stock tickers, build logs, notification feeds, and progress updates. On the frontend, you create new EventSource('/api/stream') and attach a listener. The browser keeps the connection open, parses incoming data (lines, and reconnects automatically if the network drops briefly.
Connecting with the EventSource API
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) =&gt; {
const li = document.createElement('li');
li.textContent = event.data;
feed.appendChild(li);
};source.addEventListener('status', (event) =&amp;gt; {
console.log('Named status event:', event.data);
});source.onerror = () =&amp;gt; {
console.warn('Stream interrupted; browser will attempt reconnect.');
};
}
</script>
</body>
</html>
Here is what each part does:
onmessage handles unnamed events, the default kind.
addEventListener('status', ...) handles a named event. The server sends it by adding an event: status line before the data: line.
onerror fires when the connection drops. The browser then retries on its own.
textContent inserts the data as plain text, which avoids XSS problems from untrusted messages.
How to Check It Works
Run the server, serve the HTML from the same origin, and open the page. A new list item should appear every two seconds. In DevTools, open the Network tab and click the live-events request. It should stay pending, and the EventStream view (in Chrome) lists each message. Stop the server and watch onerror log a warning, then restart it, and the stream resumes.
SSE vs. WebSockets
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.
Common SSE Mistakes
Forgetting the Double Newline
Browsers buffer incoming lines until they see a blank line marking the end of an event. If your server sends data: hello instead of data: hello , nothing appears on the page.
Hitting HTTP/1.1 Connection Limits
HTTP/1.1 browsers allow only about six open connections per domain, and each SSE stream uses one for as long as it is open. Several tabs on the same site can use them all up. Serving SSE over HTTP/2 lets streams share a single connection.
Never Closing Streams
In a single-page app, call source.close() when a component unmounts or the route changes. Otherwise, old connections and listeners pile up:
// when leaving the page or component
source.close();Proxy Buffering
In production, a reverse proxy such as Nginx may buffer responses, so events arrive in bursts instead of instantly. If messages work locally but lag on the live server, check the proxy's buffering settings and the documentation for your setup.
Conclusion
Server-Sent Events are a simple way to push one-way updates: set the right content type, end every event with a blank line, listen with EventSource, and close the stream when you're done. Reach for WebSockets only when you truly need two-way traffic. To handle the incoming data, continue with our lesson on JavaScript JSON handling.
Frequently Asked Questions (FAQs)
Does EventSource automatically reconnect when a user loses Wi-Fi briefly?
Yes. Automatic reconnection (usually after about three seconds) and Last-Event-ID tracking are part of the browser's EventSource behavior. The server can change the delay with a retry: line.
Can I send custom JSON payloads over SSE?
Yes. Put the JSON on a single data: line, such as data: {"price":42} followed by a blank line, and call JSON.parse(event.data) in your handler.
Can EventSource send custom headers?
Not with the standard API. It uses cookies and the URL, so use cookie-based sessions or a token in the URL, and keep tokens short-lived.
Does SSE work in all browsers?
It is supported in current major browsers, but check Can I use if you need older ones.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.