JAVASCRIPT
Consuming Real-Time Updates with Server-Sent Events (SSE)
Integrate real-time data streams into your web application by consuming Server-Sent Events (SSE), enabling push notifications and live updates from an API.
function setupSseConnection(sseEndpoint, onMessageCallback, onErrorCallback, onOpenCallback) {
if (!window.EventSource) {
console.error('Your browser does not support Server-Sent Events.');
return;
}
const eventSource = new EventSource(sseEndpoint);
eventSource.onopen = (event) => {
console.log('SSE connection opened.', event);
if (onOpenCallback) onOpenCallback(event);
};
eventSource.onmessage = (event) => {
console.log('Received generic SSE message:', event.data);
if (onMessageCallback) onMessageCallback(JSON.parse(event.data));
};
// Listen for custom event types if the API sends them
// eventSource.addEventListener('update', (event) => {
// console.log('Received custom update event:', event.data);
// // Handle specific 'update' event data
// });
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
if (onErrorCallback) onErrorCallback(error);
// Optionally close the connection and try to reconnect
// eventSource.close();
// setTimeout(() => setupSseConnection(sseEndpoint, onMessageCallback, onErrorCallback, onOpenCallback), 5000);
};
// Function to close the connection when no longer needed
const closeConnection = () => {
eventSource.close();
console.log('SSE connection closed.');
};
return closeConnection; // Return a function to allow external closing
}
// Usage example:
// const sseClose = setupSseConnection(
// '/api/events',
// (data) => {
// console.log('Data from SSE:', data);
// // Update UI with new data
// },
// (error) => {
// console.error('SSE connection error:', error);
// },
// () => {
// console.log('SSE connection successfully established!');
// }
// );
// // To close the connection after some time or on component unmount:
// // setTimeout(() => sseClose(), 60000);
How it works: This JavaScript snippet demonstrates how to consume real-time updates from an API using Server-Sent Events (SSE). SSE provides a persistent, one-way connection from the server to the client, allowing the server to push data updates without the client needing to constantly poll. The `EventSource` API is used to establish and manage this connection, listening for generic messages (`onmessage`) or specific named events (`addEventListener`). This pattern is ideal for dashboards, notifications, and other scenarios requiring live data streams.