One-Way Real-Time Broadcasting
Server-Sent Events (SSE) allow a server to push updates to the browser in real time. Unlike WebSocket, it's one-directional — the server talks, the browser listens.
const eventSource = new EventSource('/api/notifications');
// Default message handler
eventSource.onmessage = function(event) {
const notification = JSON.parse(event.data);
showNotification(notification.message);
};
// Named event types
eventSource.addEventListener('price-update', function(event) {
updateStockPrice(JSON.parse(event.data));
});
// Error and reconnection handling
eventSource.onerror = function() {
console.log('Connection lost — browser will auto-reconnect...');
};
// Close when done
function stopListening() {
eventSource.close();
}
SSE vs WebSocket
| Feature | SSE | WebSocket |
|---|---|---|
| Direction | Server → Browser only | Bidirectional |
| Protocol | Regular HTTP | WS / WSS |
| Auto-reconnect | ✅ Built-in | ❌ Must implement manually |
| Browser support | All modern browsers | All modern browsers |
| Best for | Notifications, feeds, live scores | Chat, games, collaborative tools |
Note
Perfect for: news feeds, notifications, currency rates, sports scores, live dashboards — any scenario where you only need data flowing from the server.