Node.js WebSocket reconnection failing on Notification API token refresh

Problem

The queue analytics view locks up at exactly 1800 seconds, and the Node.js client keeps throwing WebSocket is already in CLOSING or CLOSED state during the token swap. Auth handshake timing looks off. We’ve wired the close handler to retry the subscription, but the server kicks the session before the fresh bearer token gets injected.

socket.on('close', () => {
 setTimeout(() => socket = new WebSocket('wss://api.mypurecloud.com/api/v2/analytics/events'), 5000);
});

The connection drops right before the Authorization header sticks.

The issue is the race condition during the token swap. You’re trying to reconnect before the old socket fully closes. Wait for the close event, then fetch a new token via /api/v2/oauth/token, and finally open the new WebSocket. Here’s the pattern that works.

socket.on('close', async () => {
 const token = await getNewToken();
 connectWebSocket(token);
});