Server-Sent Events (SSE)
Server-Sent Events (SSE) is a unidirectional, lightweight way for a server to push real-time updates to the browser over a single HTTP connection. Unlike WebSockets (which are bidirectional), SSE streams data only from server → client.
🔍 How SSE Works
- Client opens a persistent HTTP connection using the
EventSource API.
- Server responds with a
Content-Type: text/event-stream header and keeps the connection open.
- Server periodically writes messages in a special format; the browser dispatches them as events.
- If the connection drops, the browser automatically tries to reconnect (configurable).
📦 Simple Example
1) Node.js Server (Express)
const express = require('express');
const app = express();
app.get('/events', (req, res) => {
res.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive'
});
let id = 0;
// send a ping every 5 seconds
const interval = setInterval(() => {
id++;
res.write(`id: ${id}\n`);
res.write(`event: ping\n`);
res.write(`data: ${JSON.stringify({ time: new Date().toISOString() })}\n\n`);
}, 5000);
// cleanup on client disconnect
req.on('close', () => {
clearInterval(interval);
});
});
app.listen(3000, () => console.log('SSE server listening on http://localhost:3000'));
2) Browser Client (HTML + JS)
<!DOCTYPE html>
<html>
<body>
<h3>Server Time Updates</h3>
<pre id="log"></pre>
<script>
const log = document.getElementById('log');
const evtSource = new EventSource('/events');
evtSource.addEventListener('ping', e => {
const msg = JSON.parse(e.data);
log.textContent += `Ping #${e.lastEventId} @ ${msg.time}\n`;
});
evtSource.onerror = err => {
console.error('EventSource failed:', err);
// evtSource.close(); // optionally stop
};
</script>
</body>
</html>
✅ When to Use SSE
- Live feeds (stock tickers, news tickers)
- Server-side notifications (build status, logs)
- Simpler than WebSockets when you only need server→client updates
⚖️ SSE vs. WebSockets
| Feature | SSE | WebSockets |
|---|
| Direction | Server → Client only | Bi-directional |
| Protocol | HTTP/1.1 (text/event-stream) | WS/WSS |
| Automatic reconnect | Built-in | You must implement |
| Ease of use | Very simple (EventSource API) | More setup & boilerplate |
Feel free to ask if you’d like more details on advanced features (custom events, reconnection strategies, authentication, etc.)!