SSE — Explained with Examples
SSE (Server-Sent Events) is a one-way push technology that enables servers to stream data to clients over a single HTTP connection.
SSE stands for Server-Sent Events, defined as part of HTML5. Unlike WebSocket, SSE is unidirectional — only the server can send messages to the client.
How SSE Works
The client opens a standard HTTP connection, and the server keeps it open, sending data as events. The browser automatically parses these events and fires JavaScript events.
// Server-side (Node.js with Express)
app.get('/events', (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// Send an event every 2 seconds
const interval = setInterval(() => {
const data = JSON.stringify({
time: new Date().toISOString(),
value: Math.random()
});
res.write(`data: ${data}\n\n`);
}, 2000);
req.on('close', () => clearInterval(interval));
});// Client-side
const eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Server says:', data);
};
eventSource.onerror = (err) => {
console.error('Connection lost, auto-reconnecting...');
};Expected output: Client receives {"time":"2026-06-19T12:00:00Z","value":0.8472} every 2 seconds.
Real-World Analogy
SSE is like a radio broadcast. The radio station (server) transmits continuously, and you (client) tune in to receive. You can’t talk back to the station through the radio — it’s one-way. If your radio loses signal, it automatically re-tunes to the right frequency (auto-reconnect).
When to Use SSE vs WebSocket
| Feature | SSE | WebSocket |
|---|---|---|
| Direction | Server → Client only | Bidirectional |
| Protocol | HTTP | WS/WSS |
| Auto-reconnect | Built-in | Must implement |
| Browser support | Excellent | Excellent |
| Best for | Notifications, feeds, logs | Chat, gaming, collaboration |
Related Terms
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro