{ "type": "order_update", "title": "Order Accepted โ ", "message": "Your payment was confirmed and the store has accepted your order.", "data": { "orderId": "507f1f77bcf86cd799439011", "orderNumber": "CB20240115001", "status": "accepted" }}
{ "type": "order_update", "title": "Order Ready for Pickup ๐", "message": "Your order is ready! Head to the store and show the OTP to collect it.", "data": { "orderId": "507f1f77bcf86cd799439011", "orderNumber": "CB20240115001", "status": "ready", "otp": "123456" }}
// Get your access token from localStorage or your auth stateconst accessToken = localStorage.getItem('accessToken');// Create EventSource connectionconst eventSource = new EventSource( `https://api.campusbite.com/api/notifications/subscribe?token=${accessToken}`);// Handle connection openedeventSource.addEventListener('open', () => { console.log('SSE connection established');});// Handle incoming messageseventSource.addEventListener('message', (event) => { const notification = JSON.parse(event.data); console.log('Notification received:', notification); if (notification.type === 'order_update') { // Update UI with order status change updateOrderStatus(notification.data); // Show notification to user showNotification(notification.title, notification.message); // If order is ready, display OTP if (notification.data.status === 'ready' && notification.data.otp) { displayOtp(notification.data.otp); } }});// Handle errorseventSource.addEventListener('error', (error) => { console.error('SSE error:', error); // EventSource will automatically try to reconnect // Close if you want to stop reconnection attempts // eventSource.close();});// Close connection when user logs out or navigates awayfunction cleanup() { eventSource.close();}
Automatic reconnection: Handled by browserโs EventSource API
Connection cleanup: Connection is automatically closed when user disconnects
The connection is persistent and will remain open until either the client closes it or the server restarts. The browser will automatically attempt to reconnect if the connection is lost.
Each user can have multiple SSE connections open (e.g., multiple tabs). All connections for the same user will receive the same notifications.