Traditionally, a web page must ask a server for data (polling). With the Server-Sent Events (SSE) API, the relationship changes: the server "pushes" updates to the web page automatically as soon as they happen.
SSE is a one-way messaging system. Data flows from the server to the browser. This is perfect for apps that need live updates without user interaction, such as:
Live stock market tickers.
Real-time news feeds.
Sports scores and play-by-play updates.
Social media notifications.
To receive updates, we use the JavaScript EventSource object.
Not all legacy browsers support SSE, so always check for compatibility first.
if (typeof(EventSource) !== "undefined") {
// Support confirmed!
} else {
document.getElementById("result").innerHTML = "Your browser does not support Server-Sent Events.";
}
You define a source URL and listen for the onmessage event.
// Connect to the server-side script
const source = new EventSource("updates.php");
// Triggered every time the server sends new data
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
For SSE to work, the server must keep the connection open and send data in a specific format. The most important part is setting the Content-Type header to text/event-stream.
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // Prevent the browser from caching old data
// Get the current server time
$currentTime = date('h:i:s A');
// Every message MUST start with "data: " and end with two newlines "\n\n"
echo "data: Current Server Time: {$currentTime}\n\n";
// Push the data to the client immediately
flush();
?>
Beyond just receiving messages, the EventSource object allows you to track the status of the connection.
| Event | Description |
|---|---|
| onopen | Triggered when the connection to the server is successfully established |
| onmessage | Triggered when the server sends a new data packet. |
| onerror | Triggered if the connection drops or an error occurs. |
| API | Chrome | Edge | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| SSE | 6.0+ | 79.0+ | 6.0+ | 5.0+ | 11.5+ |
One-Way only:If you need two-way communication (client to server AND server to client), consider using WebSockets.
Automatic Reconnection:If the connection is lost, the browser will automatically try to reconnect to the server.
Format Matters:Always ensure your server output starts with data: followed by your message.