Skip to content

HTML SSE

Server-Sent Events (SSE) enable a web page to receive automatic updates from a server via an HTTP connection.

SSE allows a server to push data to a client (web page) once an initial connection is established. This is different from traditional polling where the client repeatedly asks the server for updates.

With SSE, the updates arrive automatically from the server over a single, long-lived connection.

Common use cases: Real-time notifications (social media feeds, news updates), live data visualization (stock prices, dashboards), status updates (job progress), chat applications (receiving messages).

Server-Sent Events are supported by all major modern browsers, including Chrome, Firefox, Safari, Edge, and Opera.

Internet Explorer does not support SSE.

The EventSource JavaScript object is used to receive SSE notifications.

<!-- HTML structure -->
<div id="result"></div>
<!-- JavaScript -->
<script>
const resultElement = document.getElementById('result');
if (typeof(EventSource) !== 'undefined') {
// Create a new EventSource object, specifying the URL of the server endpoint
const source = new EventSource('sse_server.php'); // Replace with your server endpoint
// Handle incoming messages (default 'message' event)
source.onmessage = function(event) {
resultElement.innerHTML += `Data received: ${event.data}<br>`;
};
// Optional: Handle the connection opening
source.onopen = function(event) {
resultElement.innerHTML += 'Connection opened.<br>';
};
// Optional: Handle errors
source.onerror = function(event) {
resultElement.innerHTML += 'Error occurred.<br>';
// You might want to close the connection or attempt to reconnect here
// source.close();
};
} else {
resultElement.innerHTML = 'Sorry, your browser does not support Server-Sent Events.';
}
</script>

Example explained:

  • Check if EventSource is supported in the browser.
  • Create a new EventSource instance, providing the URL of the server script that will send events.
  • Listen for the onmessage event: This triggers each time the server sends a message without a specific event name.
  • The event.data property contains the message payload from the server.
  • Optionally, handle onopen and onerror events for connection status and error handling.

The server needs to send data in a specific format over an HTTP connection.

Key requirements for the server response:

  • Set the Content-Type header to text/event-stream.
  • Set appropriate cache control headers (e.g., Cache-Control: no-cache) to prevent intermediate proxies from buffering.
  • Format messages using data:, event:, id:, or retry: fields, followed by a newline (\n).
  • Separate messages with a double newline (\n\n).

Code in PHP (e.g., sse_server.php):

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // Recommended to prevent buffering
$time = date('r');
echo "data: The server time is: {$time}\n\n"; // Note the double newline
flush(); // Ensure data is sent immediately
// Example of sending multiple events or keeping connection alive
/*
while(true) {
$currentTime = date('r');
echo "data: Current time: {$currentTime}\n\n";
flush();
sleep(5); // Send update every 5 seconds
}
*/
?>

Code in Node.js (Conceptual Example):

const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
setInterval(() => {
const time = new Date().toLocaleTimeString();
res.write(`data: The server time is: ${time}\n\n`);
}, 1000);
// Send an initial message
const time = new Date().toLocaleTimeString();
res.write(`data: The server time is: ${time}\n\n`);
}).listen(3000, () => {
console.log('SSE server running on port 3000');
});

Besides the default onmessage, you can handle other events:

EventDescription
onopenFires when the connection to the server is successfully opened.
onmessageFires when a message (without a specific event name) is received from the server.
onerrorFires when an error occurs (e.g., connection lost).
Custom EventsYou can listen for custom events sent from the server using source.addEventListener('eventName', function(event) { ... }); if the server sends messages like event: eventName\ndata: ...\n\n.