JAVASCRIPT
Real-time Updates with Server-Sent Events (SSE)
Integrate real-time data streams into your web application using Server-Sent Events (SSE), enabling efficient unidirectional communication from server to client for live updates and notifications.
// --- Client-side (JavaScript in browser) ---
// Make sure your server-side endpoint '/events' correctly implements SSE
// (e.g., sets Content-Type: text/event-stream and sends data in 'data: ...
' format)
const setupSSEConnection = (endpoint) => {
// Check for EventSource support
if (typeof EventSource === 'undefined') {
console.error('EventSource is not supported by this browser.');
alert('Your browser does not support Server-Sent Events.');
return;
}
const eventSource = new EventSource(endpoint);
eventSource.onopen = () => {
console.log('SSE connection established.');
// Optionally update UI to show connection status
};
eventSource.onmessage = (event) => {
console.log('Received generic message:', event.data);
try {
const data = JSON.parse(event.data);
// Update UI with generic data
displayMessage('Generic Update: ' + JSON.stringify(data));
} catch (e) {
displayMessage('Generic Update (raw): ' + event.data);
}
};
// Listen for a custom event named 'new_notification'
eventSource.addEventListener('new_notification', (event) => {
console.log('Received new notification event:', event.data);
const notification = JSON.parse(event.data);
displayMessage(`New Notification: ${notification.message} (from ${notification.user})`);
});
// Listen for errors
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
eventSource.close(); // Close the connection on error
displayMessage('SSE Error: Connection closed. Retrying in 5s...');
// Implement a retry mechanism with exponential backoff if needed
setTimeout(() => setupSSEConnection(endpoint), 5000);
};
// Function to display messages (for demonstration)
function displayMessage(message) {
const container = document.getElementById('sse-messages');
if (!container) {
console.warn('Element with id "sse-messages" not found.');
return;
}
const p = document.createElement('p');
p.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
container.appendChild(p);
container.scrollTop = container.scrollHeight; // Scroll to bottom
}
// To close the connection explicitly (e.g., on component unmount)
// return () => {
// eventSource.close();
// console.log('SSE connection closed.');
// };
};
// Initialize SSE connection when the DOM is ready
document.addEventListener('DOMContentLoaded', () => {
// Create a div to display messages
const body = document.body;
const messageDiv = document.createElement('div');
messageDiv.id = 'sse-messages';
messageDiv.style.border = '1px solid #ccc';
messageDiv.style.padding = '10px';
messageDiv.style.marginTop = '20px';
messageDiv.style.height = '150px';
messageDiv.style.overflowY = 'auto';
messageDiv.style.backgroundColor = '#f9f9f9';
body.appendChild(messageDiv);
setupSSEConnection('/events'); // Your SSE endpoint
});
// --- Server-side (Example with Node.js Express) ---
/*
const express = require('express');
const app = express();
const port = 3000;
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders(); // Flush the headers to establish the connection
let counter = 0;
const intervalId = setInterval(() => {
// Send a generic message
res.write(`data: ${JSON.stringify({ timestamp: new Date(), value: counter })}
`);
// Send a custom event
if (counter % 3 === 0) {
res.write(`event: new_notification
`);
res.write(`data: ${JSON.stringify({ user: 'System', message: \`Item ${counter} processed!\` })}
`);
}
counter++;
}, 2000); // Send an event every 2 seconds
// Handle client disconnect
req.on('close', () => {
console.log('Client disconnected from SSE');
clearInterval(intervalId);
res.end(); // End the response
});
});
app.listen(port, () => {
console.log(`Server running for SSE at http://localhost:${port}`);
});
*/
How it works: This snippet demonstrates client-side integration of Server-Sent Events (SSE) using the `EventSource` API in JavaScript. SSE provides a unidirectional, real-time connection from a server to a client, ideal for push notifications, live feeds, and continuous updates. The code sets up an `EventSource` to a specified endpoint, listening for generic `onmessage` events and custom named events (like `new_notification`), and includes basic error handling. An example server-side setup using Node.js/Express is provided in comments to illustrate how an SSE endpoint typically sends data.