HTML SSE (Server-Sent Events) Get Certified
What are Server-Sent Events (SSE)?
Server-Sent Events allow a server to push updates to the browser over a single, long-lived HTTP connection. The client uses the EventSource interface to listen for messages. It is unidirectional (server → client only) and ideal for live feeds, notifications, and real-time dashboards.
Key Points
- Uses standard HTTP (no special protocol needed).
- Browser automatically reconnects if the connection drops.
- Simpler than WebSockets when you only need server-to-client updates.
- Content-Type on the server must be
text/event-stream.
HTML SSE Code Examples
1. Basic EventSource Usage
How the client connects and listens for messages. (A real server endpoint is required for live data.)
What this code does: Creates an EventSource connection and displays incoming messages. In a real project you would point it to your server script.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Basic SSE Example</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
#messages {
background: white;
border: 1px solid #ddd;
padding: 15px;
height: 200px;
overflow-y: auto;
margin-top: 15px;
}
</style>
</head>
<body>
<h2>Server-Sent Events Demo</h2>
<p>Status: <span id="status">Connecting...</span></p>
<div id="messages"></div>
<script>
// Note: Replace "sse-endpoint" with a real server URL that sends event-stream data
// For demonstration we simulate messages with setInterval
const messagesDiv = document.getElementById("messages");
const status = document.getElementById("status");
// Simulated SSE (because a real server is not available in this preview)
status.textContent = "Simulating SSE (no real server in preview)";
let counter = 1;
const interval = setInterval(() => {
const time = new Date().toLocaleTimeString();
messagesDiv.innerHTML += "Message " + counter + " received at " + time + "<br>";
messagesDiv.scrollTop = messagesDiv.scrollHeight;
counter++;
if (counter > 8) clearInterval(interval);
}, 1000);
/* Real EventSource code (use this with a real server):
if (typeof EventSource !== "undefined") {
const source = new EventSource("sse.php"); // your server endpoint
source.onopen = function() {
status.textContent = "Connected";
};
source.onmessage = function(event) {
messagesDiv.innerHTML += event.data + "<br>";
messagesDiv.scrollTop = messagesDiv.scrollHeight;
};
source.onerror = function() {
status.textContent = "Connection error / closed";
};
} else {
status.textContent = "SSE not supported in this browser";
}
*/
</script>
</body>
</html>
2. Listening for Custom Event Types
Servers can send named events. The client can listen for specific event names.
What this code does: Shows how to use addEventListener for both the default “message” event and custom events.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Custom SSE Events</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
#log {
background: white;
border: 1px solid #ddd;
padding: 15px;
height: 220px;
overflow-y: auto;
margin-top: 15px;
font-family: monospace;
}
</style>
</head>
<body>
<h2>Custom Event Types</h2>
<p>Listening for "message" and "update" events...</p>
<div id="log"></div>
<script>
const log = document.getElementById("log");
// Simulated custom events
const events = [
{ type: "message", data: "Welcome!" },
{ type: "update", data: "Price changed to $42" },
{ type: "message", data: "New user joined" },
{ type: "update", data: "Stock: +1.2%" }
];
let i = 0;
const interval = setInterval(() => {
if (i >= events.length) {
clearInterval(interval);
return;
}
const evt = events[i];
log.innerHTML += "[" + evt.type.toUpperCase() + "] " + evt.data + "<br>";
log.scrollTop = log.scrollHeight;
i++;
}, 1200);
/* Real code with EventSource:
const source = new EventSource("sse-endpoint");
source.addEventListener("message", function(e) {
log.innerHTML += "[MESSAGE] " + e.data + "<br>";
});
source.addEventListener("update", function(e) {
log.innerHTML += "[UPDATE] " + e.data + "<br>";
});
source.onerror = function() {
log.innerHTML += "Connection error<br>";
};
*/
</script>
</body>
</html>
3. Server-Side Format (Reference)
This is what a simple server script should output. (PHP example for reference.)
What this code does: Shows the correct format the server must send so the browser can parse the events.
<!-- This is SERVER-SIDE code (PHP example) - not run in the browser -->
<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Connection: keep-alive");
// Send a message every 2 seconds
while (true) {
echo "data: The time is " . date("H:i:s") . "\n\n";
ob_flush();
flush();
sleep(2);
}
?>
/*
Important format rules:
- Each message starts with "data: "
- End each message with two newlines (\n\n)
- Optional: event: customName
- Optional: id: 123
- Optional: retry: 5000 (reconnect time in ms)
*/
SSE vs WebSockets
- SSE – One-way (server → client), uses HTTP, automatic reconnection, simpler for live feeds.
- WebSockets – Two-way communication, more powerful for chat or collaborative apps, but more complex.
Browser Support
EventSource is supported in all modern browsers. Internet Explorer does not support it (use a polyfill if needed).
Web Resources on HTML SSE
1. MDN : Server-sent events
2. MDN : Using server-sent events
3. web.dev : Stream updates with server-sent events
Questions and Answers related to HTML SSE
SSE is a technology that lets a server push updates to the browser over a single long-lived HTTP connection. The client uses the EventSource API to receive the messages.
Create an EventSource object: const source = new EventSource("your-endpoint"). Then listen with source.onmessage or source.addEventListener("eventname", ...).
The server must send Content-Type: text/event-stream and keep the connection open while writing messages in the correct format (data: ...\n\n).
Use SSE when you only need the server to send data to the client (news feeds, stock tickers, notifications). Use WebSockets when both sides need to send messages (chat, multiplayer games).
Yes. If the connection drops, the browser automatically tries to reconnect. You can control the delay with the retry: field sent by the server.
🧪 Test Your HTML Code
Edit the HTML code on the left and click “Run Code” to see the result on the right.
Click “Run Code” to see the result here.