📡 One-Way Real-Time Updates
Need live updates but not bidirectional? EventSource (SSE) is simpler than WebSockets. Auto-reconnects. Built-in retry. Perfect for dashboards, notifications.
📝 Client-Side
const eventSource = new EventSource('/api/events');
// Listen for messages
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Update:', data);
updateUI(data);
};
// Listen for specific event type
eventSource.addEventListener('notification', (event) => {
const notification = JSON.parse(event.data);
showNotification(notification);
});
// Error handling (auto-reconnect)
eventSource.onerror = (error) => {
console.error('SSE error:', error);
// EventSource automatically tries to reconnect
};
// Close when done
// eventSource.close();
🎯 Server-Side (Node.js)
app.get('/api/events', (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*'
});
// Send message every 5 seconds
const interval = setInterval(() => {
const data = { time: new Date().toISOString(), value: Math.random() };
res.write(`data: ${JSON.stringify(data)}\n\n`);
}, 5000);
// Send notification event
setTimeout(() => {
res.write(`event: notification\n`);
res.write(`data: ${JSON.stringify({ message: 'Welcome!' })}\n\n`);
}, 1000);
req.on('close', () => clearInterval(interval));
});
✅ Use Cases
- Live sports scores, stock tickers
- Real-time dashboards (CPU, memory)
- Notification feeds
- Progress updates (file upload, batch processing)
- Social media feeds (one-way)
💡 SSE vs WebSockets
- SSE: One-way (server → client), HTTP, auto-reconnect, simpler
- WebSockets: Two-way, requires upgrade, more complex
- SSE has built-in retry and reconnection
- SSE can’t send from client to server (use fetch for that)
- Maximum 6 connections per domain (HTTP/1.1)
“Tried WebSockets for dashboard, overkill. EventSource: 10 lines of code, auto-reconnect, works perfectly. Live updates with zero headache.”
