HTML Server-Sent Events
Most web pages work on a "you ask, I answer" basis: the browser requests something and the server replies. But some information changes on its own — live sports scores, stock prices, a progress bar for a long upload, new notifications. Server-Sent Events (SSE) let the server push updates to the page over a single long-lived HTTP connection, as soon as they happen.
How it works
- The page opens a connection with
new EventSource('/updates'). - The server keeps the response open and writes small text messages whenever it has news.
- The browser fires a
messageevent for each one. - If the connection drops, the browser reconnects automatically.
SSE is one-way: server → browser. For two-way chat-style communication, use WebSockets instead.
The browser side
const source = new EventSource('/updates');
source.onopen = function () {
console.log('Connected');
};
source.onmessage = function (event) {
console.log('New data:', event.data);
};
source.onerror = function () {
console.log('Connection lost — the browser will retry');
};
// Listen for a custom event type sent with "event: score"
source.addEventListener('score', function (event) {
const score = JSON.parse(event.data);
console.log(score.home, '-', score.away);
});
// Stop listening
// source.close();The server side
The server must answer with the content type text/event-stream and then write messages in a very simple text format. Here is a minimal Node.js server (shown for explanation — it cannot run in the browser):
// server.js (Node.js)
const http = require('http');
http.createServer(function (req, res) {
if (req.url !== '/updates') { res.end('Hello'); return; }
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
let n = 0;
const timer = setInterval(function () {
n++;
res.write('data: Update number ' + n + '\n\n');
}, 2000);
req.on('close', function () { clearInterval(timer); });
}).listen(3000);The message format
Each message is one or more field: value lines followed by a blank line, which marks the end of the message.
data: Simple text message
event: score
data: {"home": 2, "away": 1}
id: 42
retry: 5000
data: First line
data: Second line| Field | Meaning |
|---|---|
data: |
The message content. Several data: lines are joined with newlines |
event: |
A custom event name; listen with addEventListener(name, …) instead of onmessage |
id: |
An id the browser remembers; after reconnecting it sends Last-Event-ID so the server can resume |
retry: |
How many milliseconds to wait before reconnecting |
: (line starting with colon) |
A comment, often sent as a "heartbeat" to keep the connection open |
The EventSource API
| Member | Purpose |
|---|---|
new EventSource(url) |
Open a connection |
onopen |
Connection established |
onmessage |
Message without an event: name |
onerror |
Connection problem (the browser retries) |
addEventListener(type, fn) |
Listen for named events |
readyState |
0 connecting, 1 open, 2 closed |
close() |
Close the connection for good |
A simulation
There is no server inside a playground, so this example simulates an SSE stream: it splits a hard-coded text stream into messages using the same rules a browser follows (blank line ends a message, event: sets the type, data: lines are joined) and "delivers" them one per second.
<!DOCTYPE html>
<html>
<body>
<h3>Live match (simulated stream)</h3>
<p id="score">Waiting for kick-off…</p>
<ul id="log"></ul>
<script>
const stream =
'event: score\ndata: {"home":0,"away":0}\n\n' +
'data: Kick-off!\n\n' +
'event: score\ndata: {"home":1,"away":0}\n\n' +
'data: Half-time\n\n' +
'event: score\ndata: {"home":1,"away":1}\n\n' +
'data: Full-time\n\n';
// Parse the text into messages, like EventSource does
const messages = stream.split('\n\n').filter(Boolean).map(function (block) {
const msg = { type: 'message', data: [] };
block.split('\n').forEach(function (line) {
const i = line.indexOf(':');
const field = line.slice(0, i), value = line.slice(i + 1).trim();
if (field === 'event') msg.type = value;
if (field === 'data') msg.data.push(value);
});
msg.data = msg.data.join('\n');
return msg;
});
function handle(msg) {
if (msg.type === 'score') {
const s = JSON.parse(msg.data);
document.getElementById('score').textContent = 'Home ' + s.home + ' – ' + s.away + ' Away';
} else {
const li = document.createElement('li');
li.textContent = msg.data;
document.getElementById('log').appendChild(li);
}
}
messages.forEach(function (m, i) { setTimeout(function () { handle(m); }, (i + 1) * 1000); });
</script>
</body>
</html>With a real server, you would replace the parsing and timers with new EventSource('/match') and the same handle logic inside the listeners.
SSE vs alternatives
| Technique | Direction | Notes |
|---|---|---|
Polling (fetch every few seconds) |
Browser asks repeatedly | Simple but wasteful and laggy |
| Server-Sent Events | Server → browser | Plain HTTP, auto-reconnect, text only |
| WebSockets | Both ways | Best for chat and games; more complex |
Tip: SSE works through most proxies because it is ordinary HTTP. Remember to send a comment line (
: ping) every 15–30 seconds so idle connections are not closed by servers in between.
Test yourself
Which object does the browser use to receive Server-Sent Events?
WebSocketEventSourceXMLHttpRequestWorker
What ends a single message in the event stream?
- A semicolon
- A blank line
- The word
end - A closing tag
When should you choose WebSockets over SSE?
- When only the server sends updates
- When both the browser and server need to send messages frequently
- When you want automatic reconnection
- Never