📡 Server-Sent Events = One-Way Real-Time
WebSockets are bidirectional. SSE is one-way. Real-time updates, notifications, live feeds — simpler than WebSockets.
📝 SSE Basics
// Client-side
const eventSource = new EventSource('/api/events');
// Listen for messages
eventSource.onmessage = function(event) {
console.log('Message:', event.data);
const data = JSON.parse(event.data);
updateUI(data);
};
// Handle specific event types
eventSource.addEventListener('user-joined', function(event) {
console.log('User joined:', event.data);
});
eventSource.addEventListener('update', function(event) {
const data = JSON.parse(event.data);
updateDashboard(data);
});
// Error handling
eventSource.onerror = function(error) {
console.error('SSE error:', error);
eventSource.close();
};
// Close connection
eventSource.close();
// Server-side (Node.js)
app.get('/api/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
let counter = 0;
const interval = setInterval(() => {
res.write(`data: ${JSON.stringify({
id: counter++,
time: new Date().toISOString()
})}\n\n`);
}, 1000);
req.on('close', () => {
clearInterval(interval);
res.end();
});
});
🎯 Advanced SSE
// Server with custom event types
app.get('/api/notifications', (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// Send different event types
const events = [
{ type: 'notification', data: { message: 'New message' } },
{ type: 'alert', data: { level: 'warning', text: 'Server load high' } },
{ type: 'update', data: { progress: 50 } }
];
events.forEach(event => {
res.write(`event: ${event.type}\n`);
res.write(`data: ${JSON.stringify(event.data)}\n\n`);
});
});
// Client with event types
const source = new EventSource('/api/notifications');
source.addEventListener('notification', function(e) {
const data = JSON.parse(e.data);
showNotification(data.message);
});
source.addEventListener('alert', function(e) {
const data = JSON.parse(e.data);
showAlert(data.level, data.text);
});
// Reconnection with custom ID
// Server sends id
res.write(`id: ${eventId}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
// Client reconnects with last event id
const source = new EventSource('/api/events', {
headers: { 'Last-Event-ID': lastEventId }
});
💡 SSE vs WebSockets
- SSE: One-way, simple, automatic reconnection
- WebSockets: Bidirectional, complex, full-duplex
- SSE for server-to-client updates
- WebSockets for chat, games
- SSE is simpler to implement
“SSE simplifies real-time updates. Notifications, feeds, dashboards. Essential for one-way streaming.”
