Server-Sent Events (SSE) let a web page automatically receive updates from a server. Unlike normal web pages that have to ask for new data, SSE pushes updates to you as soon as they happen.
What is Server-Sent Events?
Normally, a web page has to ask the server for new data. This is called “polling”. The page asks “Any new data?” every few seconds. This wastes resources.
With Server-Sent Events, the server pushes data to the page whenever it is ready. The page just listens. No repeated asking. No wasted requests.
Examples of SSE in action:
- Live sports scores updating automatically
- Stock market price tickers
- News feeds with breaking news
- Social media notifications
- Real-time weather updates
Browser Support
Server-Sent Events are supported in all modern browsers:
| Feature | Chrome | Edge | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| Server-Sent Events | 6.0 | 79.0 | 6.0 | 5.0 | 11.5 |
How Server-Sent Events Work
SSE works in three simple steps:
- Create an EventSource object – Point it to a server script that sends updates
- Listen for messages – The
onmessageevent fires whenever data arrives - Update the page – Display the received data on your webpage
Complete SSE Example
Here is a complete example that would work on a real server. The client code listens for updates, and the server sends the current time every few seconds.
<!DOCTYPE html>
<html>
<body>
<h3>Real-Time Server Time</h3>
<div id="result">Waiting for updates...</div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Server-Sent Events.";
}
</script>
</body>
</html>
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: The server time is: " & now())
Response.Flush()
%>
How the Server Script Works
The server script is the most important part. It must send data in a specific format:
- Content-Type header – Must be
text/event-stream - Cache-Control header – Should be
no-cacheto prevent caching - Data format – Each message must start with
data:followed by a space, then the message - End of message – Each message must end with two newlines (
\n\n) - Flush – The output must be flushed to send it immediately
Here is a more advanced PHP script that sends updates every 5 seconds:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
while (true) {
$time = date('H:i:s');
echo "data: Current server time: " . $time . "\n\n";
ob_flush();
flush();
sleep(5);
}
?>
This script runs forever, sending the current time every 5 seconds.
The EventSource Object Events
The EventSource object has three events you can listen for:
| Event | Description | When It Fires |
|---|---|---|
onopen
| Connection opened | When the connection to the server is first established |
onmessage
| Message received | When the server sends a message (most common) |
onerror
| Error occurred | When the connection fails or the server closes it |
var source = new EventSource("demo_sse.php");
source.onopen = function() {
console.log("Connection opened!");
};
source.onmessage = function(event) {
console.log("Message received: " + event.data);
document.getElementById("result").innerHTML = event.data;
};
source.onerror = function() {
console.log("Connection error!");
document.getElementById("result").innerHTML = "Connection lost. Trying to reconnect...";
};
Closing the Connection
If you no longer need updates, you can close the connection to save resources:
// Close the connection
source.close();
After closing, you can create a new EventSource later if needed.
Real-World Uses for Server-Sent Events
- Live sports scores – Update scores as they happen
- Stock market tickers – Show real-time stock prices
- News feeds – Push breaking news immediately
- Weather updates – Show changing weather conditions
- Social media notifications – Show new likes or comments on ModafVibe or other platforms
- Chat applications – Show new messages (though WebSockets are better for two-way chat)
- Progress updates – Show upload or processing progress
Quick Summary
- SSE lets servers push updates to web pages automatically.
- Use
new EventSource("server_script.php")to start listening. - Use
source.onmessageto handle incoming messages. - The server must send data starting with
data:and ending with two newlines. - The server must set
Content-Type: text/event-stream. - Use
source.close()to stop receiving updates. - SSE is one-way (server to client). Use WebSockets for two-way communication.
What Just Happened? Let Me Explain
- Traditional web pages ask “Any new data?” every few seconds. This wastes bandwidth and server resources.
- SSE keeps one connection open. The server sends data whenever it is ready. No wasted requests.
- The connection stays open until either the server closes it or you call
close(). - If the connection drops, the browser automatically tries to reconnect. You do not have to write code for that.
- SSE is simpler than WebSockets for one-way communication. Use SSE when you only need updates from the server, like news feeds or stock prices.
- For chat applications where users also send messages, WebSockets are better because they support two-way communication.
Server-Sent Events API Reference
| Method / Event / Property | Description |
|---|---|
new EventSource(url)
| Creates a connection to the server | source.onopen = function()
| Fires when the connection is opened |
source.onmessage = function(event)
| Fires when a message is received (event.data contains the message) |
source.onerror = function()
| Fires when an error occurs or connection is lost |
source.close()
| Closes the connection |
Server header: Content-Type: text/event-stream
| Required header for SSE to work |
Server header: Cache-Control: no-cache
| Prevents the browser from caching the response |
Message format: data: message\n\n
| |