I’m building a Node.js service to listen to the /api/v2/analytics/events WebSocket endpoint. The initial connection works fine using the ws library, but when the server closes the connection (usually after 5 minutes), my reconnection logic gets into a tight loop or fails to re-authenticate properly.
The issue seems to be that I’m not handling the close event correctly. My current setup looks like this:
ws.on('close', (code, reason) => {
console.log('Connection closed:', code);
// Wait 2 seconds before reconnecting
setTimeout(() => {
connect();
}, 2000);
});
The problem is that connect() reuses the old Authorization header, which might be stale if the JWT expired during the disconnect. I’m getting 401 Unauthorized errors immediately after reconnecting. I need a way to fetch a fresh OAuth token before attempting the WebSocket handshake. Should I be using the genesys-cloud-node SDK’s auth helper here, or is there a better pattern for handling token refresh in a raw WebSocket context? I don’t want to implement a full retry backoff strategy yet, just need the auth part to work reliably.