Skip to main content

HTML Server-Sent Events

In this tutorial, we will learn about HTML Server-Sent Events (SSE), a feature in HTML5 that enables real-time communication between the server and client. SSE is useful when you need to send updates from the server to the client without requiring the client to make requests constantly.

What are Server-Sent Events?

Server-Sent Events are a standardized way to send real-time updates from the server to the client over a single HTTP connection. Unlike WebSockets, SSE only allows for one-way communication, from server to client.

Creating an Event Source

To use SSE, you need to create an EventSource object in your JavaScript code. This object will open a connection to the server and listen for events. You can then handle those events using JavaScript event listeners.

Here's a simple example:

<!DOCTYPE html>
document.addEventListener('DOMContentLoaded', function () {
const source = new EventSource('events.php');

source.onmessage = function (event) {
document.getElementById('updates').innerHTML += + '<br>';
<h1>Server-Sent Events Example</h1>
<div id="updates"></div>

In this example, we create an EventSource object with the URL events.php. The server-side script at this URL will be responsible for sending events.

Sending Events from the Server

Now we need to create the server-side script (events.php in our example) that sends events to the client. Here's a simple PHP example:

header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Connection: keep-alive");

$time = date("r");
echo "data: The server time is: {$time}\n\n";

This PHP script sets the appropriate headers for an SSE connection and sends the current server time as a message. Note the use of the data: prefix and the double newline at the end, which are necessary for the SSE format.

Handling Connection Errors and Reconnections

Sometimes the connection to the server might be lost. In such cases, the EventSource object will automatically attempt to reconnect. You can also handle connection errors and reconnections using the onerror and onopen event listeners:


source.onerror = function (event) {
console.log('Error connecting to the server');

source.onopen = function (event) {
console.log('Connection reestablished');


Now you have learned how to use HTML Server-Sent Events to enable real-time updates in your web applications. Experiment with different event types and payloads to enhance your applications' interactivity and responsiveness.