On this page11 sections
  1. Learning Objectives
  2. 1. How It Works
  3. 2. The Page
  4. 3. The Server (PHP)
  5. 4. Named Events
  6. 5. Stopping
  7. The Message Format
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 048: Server-Sent Events API

Category8: Web APIs
Lecture048 of 048
Estimated video length10 min
TargetHTML5 · any modern browser
LevelIntermediate

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

output
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 htdocs and open the page through http://localhost/.


2. The Page

html
<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
<?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
<?php
echo "event: score\n";
echo "data: Pakistan 245/6\n\n";
html
<script>
  const source = new EventSource('updates.php');
  source.addEventListener('score', (event) => {
    document.getElementById('score').textContent = event.data;
  });
</script>

5. Stopping

javascript
source.close();

The Message Format

LineMeaning
data: …The message text (several data: lines are joined)
event: nameA named event type
id: 42An id; after a reconnect, the browser tells the server the last one it got
retry: 5000Wait 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

  1. In which direction do server-sent events travel?
  2. Which JavaScript object opens an SSE connection?
  3. What content type must the server send?
  4. How does each message end?
  5. How do you listen for an event called price?
  6. What do you use for two-way, real-time communication instead?

Practice Answers

  1. From the server to the browser only.
  2. EventSource
  3. text/event-stream
  4. With a blank line (\n\n).
  5. source.addEventListener('price', handler);
  6. WebSockets.

Key Takeaways

  • SSE lets a server push updates over one long-lived connection.
  • new EventSource(url) + onmessage on the page.
  • Server: Content-Type: text/event-stream, data: … lines, blank line between messages.
  • Reconnection is automatic; close() stops it.