Using the Server-Sent Events (SSE) API for Real-time Updates

Learn how to implement real-time, one-way communication between a server and a web page using the Server-Sent Events (SSE) API. This tutorial covers browser compatibility, receiving events with the `EventSource` object, handling errors, and includes server-side code examples (PHP).



Using the Server-Sent Events (SSE) API

The Server-Sent Events (SSE) API enables web pages to receive updates pushed from a server, creating a one-way communication channel for real-time data.

How Server-Sent Events Work

SSE provides a simple mechanism for a server to send updates to a web page without requiring the page to constantly poll for changes. This is efficient and ideal for applications needing real-time data streams (e.g., live updates, stock tickers).

Browser Support

Browser Version
Chrome 6.0+
Edge 79.0+
Firefox 6.0+
Safari 5.0+
Opera 11.5+

Receiving Server-Sent Events

The `EventSource` object handles receiving SSE notifications from the server. The server sends data in a specific format.

Example: Receiving SSE Events

let source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
  document.getElementById("result").innerHTML += event.data + "<br>";
};

This creates an `EventSource` object, pointing to the server-side script (`demo_sse.php`), which sends the data. The `onmessage` event handler receives and displays the data.

Checking for SSE Support

It's good practice to check if the browser supports SSE before using the `EventSource` object.

Example: Checking for SSE Support

if (typeof(EventSource) !== "undefined") {
  // SSE supported; initialize EventSource
} else {
  // SSE not supported; display a message
}

Server-Side Code (Example: PHP)

The server needs to send data in a specific format. The `Content-Type` header must be set to `"text/event-stream"`. Data is sent as lines starting with `"data: "`.

Example: PHP Server-Side Code

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

while (true) {
  echo "data: The time is " . date('H:i:s') . "\n\n";
  ob_flush();
  flush();
  sleep(1);
}
?>

(Similar examples in ASP (VB) would be added here.)

`EventSource` Object Events

The `EventSource` object triggers events when a connection is opened, messages arrive, or errors occur:

Event Description
onopen Connection to server opened.
onmessage Message received from the server.
onerror An error occurred.