HTML SSE
Server-Sent Events (SSE) is a simple one-way streaming protocol: the server pushes text events to the browser over a single long-lived HTTP connection.
How it works
- The browser opens an
EventSourceto a URL. - The server keeps the response open and writes events in a tiny line-based format.
- Each event triggers a
messageevent on the client. - If the connection drops, the browser reconnects automatically.
Client side
const stream = new EventSource('/updates');
stream.onmessage = function (e) {
console.log('Update:', e.data);
};
stream.addEventListener('price', e => {
console.log('Named price event:', e.data);
});
stream.onerror = () => console.warn('Connection lost — will reconnect.');
SSE vs WebSocket
| SSE | WebSocket | |
|---|---|---|
| Direction | Server → client only. | Both ways. |
| Protocol | HTTP. | Custom ws://. |
| Auto-reconnect | Built in. | You write it. |
| Best for | Live feeds, progress, notifications. | Chat, games, collaborative editing. |
Tip: SSE is enough for most "push" use cases. Only reach for WebSocket when the client also needs to send messages frequently.
Example
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML SSE</title>
</head>
<body>
<h1>HTML SSE</h1>
<p>This is a demo page for the "HTML SSE" lesson.</p>
</body>
</html>
Try it Yourself »
Exercise
Open a server-sent events stream.
const es = new
('/stream');
Two words concatenated in PascalCase.
Discussion
Loading…