SSE - Smart-Cart-System/backend-fastapi GitHub Wiki
Server-Sent Events (SSE) Module Documentation for Frontend
Endpoints
1. Subscribe to SSE Events
- URL:
/sse/{cart_id}
- Method:
GET
- Description: Establishes a Server-Sent Events connection for real-time cart updates.
- Path Parameters:
cart_id
(str): The unique identifier of the cart to monitor.
- Response:
SSE Message Schemas
1. SSEMessage
- Fields:
event
(str): The type of event that occurred.
data
(Dict[str, Any]): Event-specific data payload.
2. SSEAuthMessage
- Fields:
session_id
(int): The ID of the customer session.
token
(str): Bearer authentication token.
event_type
(str): Type of authentication event.
SSE Event Types
Connection Events
- Initial Connection
Authentication Events
- Session Started
QR Token to SSE Pipeline Documentation
Complete Flow from QR Generation to SSE Notification
Step 1: QR Code Generation
GET /customer-session/qr/{cart_id}
- Frontend cart requests QR code for specific
cart_id
- Server generates time-limited JWT token containing cart information
- QR code is created containing the token
- QR code displayed on cart screen
Step 2: Mobile App SSE Connection
GET /sse/{cart_id}
Step 3: QR Code Scanning
POST /customer-session/scan-qr
Step 4: SSE Authentication Event
- Immediately after successful QR scan, SSE event is triggered:
await send_authenticated_message(
cart_id=new_session.cart_id,
auth_message=SSEAuthMessage(
session_id=new_session.session_id,
token=user_bearer_token,
event_type="session-started"
)
)
Frontend Implementation Guide
Establishing SSE Connection
// Connect to SSE endpoint
const cartId = "cart_123";
const eventSource = new EventSource(`/sse/${cartId}`);
// Handle incoming messages
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
switch(data.type || data.event_type) {
case 'connection':
console.log('Connected to cart:', data.message);
break;
case 'session-started':
// Store session details
localStorage.setItem('session_id', data.session_id);
localStorage.setItem('auth_token', data.token);
// Navigate to shopping interface
navigateToShopping();
break;
case 'checkout-completed':
// Show receipt or success page
showReceipt(data);
break;
}
};
// Handle connection errors
eventSource.onerror = function(event) {
console.error('SSE connection error:', event);
};
QR Code Scanning Integration
// After scanning QR code
async function processQRScan(qrToken) {
try {
const response = await fetch('/customer-session/scan-qr', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${userToken}`
},
body: JSON.stringify({ token: qrToken })
});
// Session creation response
const sessionData = await response.json();
// SSE will automatically receive session-started event
// No need to manually handle - SSE listener will trigger
} catch (error) {
console.error('QR scan failed:', error);
}
}
Error Handling
Common Scenarios
- Invalid QR Token: HTTP 401 - "Invalid or expired QR code"
- Connection Lost: SSE
onerror
event - implement reconnection logic
- Session Creation Failed: HTTP 400 - Handle gracefully in QR scan response
Best Practices
- Implement SSE reconnection logic for network interruptions
- Store
session_id
and token
from SSE events for subsequent API calls
- Handle multiple event types in single SSE message handler
- Close SSE connection when user leaves cart context
- Validate cart_id matches expected cart before processing events
Security Considerations
- SSE connection uses cart_id (public identifier)
- Sensitive data (user tokens, session details) only sent after authentication
- JWT tokens in QR codes have short expiration times
- Bearer tokens for API access transmitted securely through SSE