JAVASCRIPT
Consuming Server-Sent Events (SSE) for Real-time Updates
Implement real-time data streaming in your web application by consuming Server-Sent Events (SSE) using the native EventSource API for efficient live updates from a server.
function connectToServerSentEvents(url) {
if (typeof EventSource === 'undefined') {
console.error('EventSource is not supported by this browser.');
return;
}
const eventSource = new EventSource(url);
eventSource.onopen = (event) => {
console.log('SSE connection opened.', event);
};
// Listen for generic messages (unnamed events)
eventSource.onmessage = (event) => {
console.log('Received generic message:', event.data);
// Parse event.data as JSON if your server sends JSON
// const data = JSON.parse(event.data);
// console.log('Parsed data:', data);
};
// Listen for custom named events (e.g., 'priceUpdate')
eventSource.addEventListener('priceUpdate', (event) => {
console.log('Received price update:', event.data);
});
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
if (eventSource.readyState === EventSource.CLOSED) {
console.log('SSE connection closed unexpectedly. Attempting to reconnect...');
// Implement reconnection logic here, e.g., setTimeout(connectToServerSentEvents, 3000, url);
}
};
// Optional: close the connection when no longer needed
// setTimeout(() => {
// eventSource.close();
// console.log('SSE connection closed after a timeout.');
// }, 60000);
return eventSource; // Return the EventSource instance if you need to close it later
}
// Example Usage:
const sseConnection = connectToServerSentEvents('https://api.example.com/events/stream');
// To close the connection when the component unmounts or page navigates
// window.addEventListener('beforeunload', () => {
// if (sseConnection) {
// sseConnection.close();
// console.log('SSE connection closed on page unload.');
// }
// });
How it works: This JavaScript snippet demonstrates how to consume Server-Sent Events (SSE) using the native `EventSource` API for real-time data updates. SSE provides a unidirectional stream from the server to the client, ideal for live dashboards, stock tickers, or news feeds without the overhead of WebSockets for simple server-to-client communication. It automatically handles reconnection and allows listening for both generic and custom-named events, offering an efficient alternative to continuous polling.