HTML Server-Sent Events (SSE) API
π Introduction to Server-Sent Events (SSE)
The Server-Sent Events (SSE) API allows a web page to receive automatic updates from a server via a persistent HTTP connection. Unlike WebSockets, SSE is unidirectional β the server pushes data, and the client listens. Itβs great for live feeds, notifications, and real-time updates! π
>>βStream data effortlessly from server to browser in real-time.β π
π How SSE Works
The browser opens a connection to the server using the EventSource interface. The server sends text-based event streams, and the browser handles them via JavaScript event listeners.
βοΈ Basic SSE Client Example
Create an EventSource and Listen for Messages
if (!!window.EventSource) {
const source = new EventSource('/sse-endpoint');
source.onmessage = function(event) {
console.log('New message:', event.data);
// Update your UI with event.data
};
source.onerror = function(event) {
console.error('SSE error:', event);
source.close();
};
} else {
console.log('Your browser does not support Server-Sent Events.');
}π₯οΈ Server Side (Example in Node.js)
A simple SSE server sends properly formatted event streams with headers:
Node.js SSE Server Example
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/sse-endpoint') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
let count = 0;
const interval = setInterval(() => {
count++;
res.write(`data: Message ${count}\n\n`);
if (count === 10) {
clearInterval(interval);
res.end();
}
}, 1000);
} else {
res.writeHead(404);
res.end();
}
}).listen(3000);π SSE Event Format
The server sends events in this format:
SSE Event Format
data: This is the message text
data: You can send multiple lines
(a blank line signals end of event)π§ Benefits of SSE
- Simple to implement compared to WebSockets for one-way communication.
- Uses standard HTTP protocol, so works through firewalls and proxies easily.
- Automatic reconnection, event IDs, and event types supported.
β οΈ Limitations
- Only supports server-to-client (unidirectional) communication.
- Not supported in Internet Explorer and some older browsers.
π§ Tips & Best Practices
- Set appropriate HTTP headers (Content-Type: text/event-stream).
- Keep the connection alive by sending periodic comments or events.
- Handle network errors and reconnection on the client side.
- Use event IDs to resume connections after interruptions.
π Useful Resources
>>βServer-Sent Events provide a lightweight way to push real-time updates from server to client.β β‘