HTML SSE
HTML Server-Sent Events API
The Server-Sent Events (SSE) API allows a web page to receive automatic updates from a server over a persistent HTTP connection.
With SSE, the server pushes data to the browser without the client repeatedly requesting it.
What Are Server-Sent Events?
Server-sent events enable one-way communication from the server to the client.
Once a connection is established, the server can continuously send updates to the web page.
Common use cases include:
- Live news feeds
- Social media updates
- Stock market data
- Sports scores
Browser Support
The Server-Sent Events API is supported by most modern browsers.
It is not supported in older or legacy environments.
Receiving Server-Sent Events
The EventSource object is used to listen for server-sent updates.
const x = document.getElementById("result"); if (typeof(EventSource) !== "undefined") { const source = new EventSource("demo_sse.php"); source.onmessage = function(event) { x.innerHTML += event.data + "<br>"; }; } else { x.innerHTML = "Sorry, server-sent events are not supported."; } How It Works
- An
EventSourceconnection is opened to the server - The server sends updates over the same connection
- The
onmessageevent fires whenever new data arrives
Checking Browser Support
Always verify that the browser supports Server-Sent Events.
if (typeof(EventSource) !== "undefined") { // SSE is supported } else { // SSE is not supported } Server-Side Requirements
The server must send data using the text/event-stream MIME type.
Each message must begin with data: and end with a blank line.
PHP Example
<?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(); ?> ASP Example
<% Response.ContentType = "text/event-stream" Response.Expires = -1 Response.Write("data: The server time is: " & now()) Response.Flush() %> Server-Side Rules
- Set
Content-Typetotext/event-stream - Disable caching
- Prefix each message with
data: - Flush output immediately
The EventSource Object
The EventSource object provides multiple event handlers.
onopen– triggered when the connection is openedonmessage– triggered when a message is receivedonerror– triggered when an error occurs
The Server-Sent Events API is ideal for real-time updates where data flows from the server to the client.