JAVASCRIPT
Integrate Real-time Data with Server-Sent Events (SSE)
Integrate Server-Sent Events (SSE) to establish persistent, one-way connections for real-time data updates from an API, ideal for live dashboards.
const eventSourceUrl = 'https://api.example.com/events/stream'; // Your SSE endpoint
let eventSource = null;
function connectToSSE() {
if (eventSource) {
console.log('Already connected to SSE.');
return;
}
console.log('Attempting to connect to SSE stream...');
eventSource = new EventSource(eventSourceUrl);
// Listen for generic messages (unnamed events)
eventSource.onmessage = (event) => {
console.log('Received generic message:', event.data);
try {
const data = JSON.parse(event.data);
console.log('Parsed generic data:', data);
// Update UI or application state with received data
} catch (e) {
console.error('Failed to parse generic SSE message:', e);
}
};
// Listen for specific named events (if your server sends them)
eventSource.addEventListener('user_update', (event) => {
console.log('Received user_update event:', event.data);
try {
const userUpdate = JSON.parse(event.data);
console.log('Parsed user update:', userUpdate);
// Update UI for user changes
} catch (e) {
console.error('Failed to parse user_update SSE message:', e);
}
});
eventSource.onopen = () => {
console.log('SSE connection opened.');
// Reconnection logic could be reset here
};
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
// Handle error, e.g., attempt to reconnect after a delay
if (eventSource.readyState === EventSource.CLOSED) {
console.log('SSE connection closed. Attempting to reconnect in 5 seconds...');
eventSource.close(); // Ensure it's closed
eventSource = null; // Clear the instance
setTimeout(connectToSSE, 5000);
}
};
}
function disconnectFromSSE() {
if (eventSource) {
eventSource.close();
eventSource = null;
console.log('SSE connection closed.');
}
}
// Example usage:
// Call connectToSSE() when your application starts or a component mounts.
// Call disconnectFromSSE() when the component unmounts or user navigates away.
// connectToSSE();
How it works: This snippet demonstrates how to integrate with a real-time API using Server-Sent Events (SSE). An `EventSource` object is created to establish a persistent, one-way connection to the specified URL. It listens for `message` events (for generic data) and can also listen for custom named events (e.g., `user_update`). The `onopen` and `onerror` handlers provide feedback on connection status and include basic reconnection logic for handling disconnections, making it suitable for dynamic, live data updates.