WebSocket Real-time Updates
SpatialFlow provides WebSocket connections for streaming real-time device locations, geofence events, and dashboard statistics without polling.
Overview
WebSockets enable your application to receive instant updates as devices move and trigger geofence events. Two channels are available:
| Channel | URL | Purpose |
|---|---|---|
| Dashboard | wss://api.spatialflow.io/ws/dashboard/events/ | Aggregated stats and live activity feed |
| Geofence Events | wss://api.spatialflow.io/ws/events/geofence/ | Real-time geofence entry/exit events |
Authentication
Pass your JWT token as a query parameter when connecting:
wss://api.spatialflow.io/ws/dashboard/events/?token=YOUR_JWT_TOKEN
The server validates the token on connection. If the token is invalid or expired, the connection is rejected.
Connecting
JavaScript Example
const token = 'YOUR_JWT_TOKEN';
const ws = new WebSocket(`wss://api.spatialflow.io/ws/dashboard/events/?token=${token}`);
ws.onopen = () => {
console.log('Connected to SpatialFlow WebSocket');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data.type, data);
};
ws.onclose = (event) => {
console.log('Disconnected:', event.code, event.reason);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
Python Example
import asyncio
import websockets
import json
async def connect():
token = "YOUR_JWT_TOKEN"
uri = f"wss://api.spatialflow.io/ws/dashboard/events/?token={token}"
async with websockets.connect(uri) as ws:
async for message in ws:
data = json.loads(message)
print(f"Received: {data['type']}")
Message Types
Dashboard Channel
| Message Type | Description | Payload |
|---|---|---|
dashboard_update | Updated dashboard metrics | { active_geofences, active_workflows, active_devices, executions_24h, ... } |
recent_events | Recent geofence events on connect | { events: [...] } |
Geofence Events Channel
| Message Type | Description | Payload |
|---|---|---|
geofence_enter | Device entered a geofence | { geofence_id, geofence_name, device_id, location, timestamp } |
geofence_exit | Device exited a geofence | { geofence_id, geofence_name, device_id, location, timestamp } |
recent_events | Recent geofence events on connect | { events: [...] } |
Message Format
Messages are flat JSON objects with a type field identifying the event kind. Here is an example geofence entry event:
{
"type": "geofence_enter",
"geofence_id": "123e4567-e89b-12d3-a456-426614174000",
"geofence_name": "Downtown Delivery Zone",
"device_id": "truck-005",
"location": {
"latitude": 37.7749,
"longitude": -122.4194
},
"timestamp": "2026-02-05T14:30:00Z"
}
Reconnection Strategy
WebSocket connections can drop due to network issues. Implement automatic reconnection with exponential backoff:
function connectWithRetry(url, maxRetries = 10) {
let retries = 0;
function connect() {
const ws = new WebSocket(url);
ws.onopen = () => {
console.log('Connected');
retries = 0; // Reset on successful connection
};
ws.onclose = (event) => {
if (retries < maxRetries) {
const delay = Math.min(1000 * Math.pow(2, retries), 30000);
console.log(`Reconnecting in ${delay}ms...`);
retries++;
setTimeout(connect, delay);
}
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
handleMessage(data);
};
return ws;
}
return connect();
}
Next Steps
- Devices - Send device location updates
- Geofences - Create geofence boundaries
- Route Tester - Test routes against geofences
- Error Handling - Handle connection errors