On this page11 sections
Lecture 048: Server-Sent Events API
| Category | 8: Web APIs |
| Lecture | 048 of 048 |
| Estimated video length | 10 min |
| Target | HTML5 · any modern browser |
| Level | Intermediate |
Usually the browser asks and the server answers. With Server-Sent Events (SSE), the page opens one connection, and the server keeps pushing updates down it whenever it has news: live scores, prices, notifications, progress bars.
Learning Objectives
- Explain how server-sent events differ from normal requests
- Receive updates with
EventSource - Handle named events and errors
- Write a tiny SSE server in PHP
1. How It Works
Browser ── "keep this open" ──▶ Server
Browser ◀── update 1 ───────── Server
Browser ◀── update 2 ───────── Server (whenever the server wants)- It's one-way: server → browser.
- The browser reconnects automatically if the connection drops.
- For two-way chat, developers use WebSockets instead.
SSE needs a server, so these examples have no Run button. Try them with XAMPP or any PHP server: put both files in
htdocsand open the page throughhttp://localhost/.
2. The Page
<h3>Live updates</h3>
<ul id="log"></ul>
<script>
const source = new EventSource('updates.php');
source.onmessage = (event) => {
const li = document.createElement('li');
li.textContent = event.data;
document.getElementById('log').append(li);
};
source.onerror = () => {
console.log('Connection lost. The browser will retry automatically.');
};
</script>3. The Server (PHP)
The response must have the type text/event-stream. Each message is a line starting with
data:, followed by a blank line.
<?php
// updates.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
for ($i = 1; $i <= 5; $i++) {
echo "data: Update {$i} at " . date('H:i:s') . "\n\n";
ob_flush();
flush();
sleep(2);
}The page shows a new line every two seconds.
4. Named Events
The server can label messages with event:. The page listens for each name separately.
<?php
echo "event: score\n";
echo "data: Pakistan 245/6\n\n";<script>
const source = new EventSource('updates.php');
source.addEventListener('score', (event) => {
document.getElementById('score').textContent = event.data;
});
</script>5. Stopping
source.close();The Message Format
| Line | Meaning |
|---|---|
data: … | The message text (several data: lines are joined) |
event: name | A named event type |
id: 42 | An id; after a reconnect, the browser tells the server the last one it got |
retry: 5000 | Wait 5 seconds before reconnecting |
| (blank line) | End of this message |
Common Beginner Mistakes
1. Missing blank line. Without \n\n, the browser waits forever for the message to end.
2. Wrong content type. It must be text/event-stream.
3. Output buffering. PHP may hold messages back. Call ob_flush() and flush().
4. Expecting two-way communication. SSE only goes from server to browser.
Practice Questions
- In which direction do server-sent events travel?
- Which JavaScript object opens an SSE connection?
- What content type must the server send?
- How does each message end?
- How do you listen for an event called
price? - What do you use for two-way, real-time communication instead?
Practice Answers
- From the server to the browser only.
EventSourcetext/event-stream- With a blank line (
\n\n). source.addEventListener('price', handler);- WebSockets.
Key Takeaways
- SSE lets a server push updates over one long-lived connection.
new EventSource(url)+onmessageon the page.- Server:
Content-Type: text/event-stream,data: …lines, blank line between messages. - Reconnection is automatic;
close()stops it.