Building a custom Node.js wrapper for the Genesys Cloud Notification API using the ws library. The initial connection and subscription to routing/queue/statistics works fine. The problem is the reconnection logic after a network blip.
I’m tracking the close event. When the server sends a 1006 (abnormal closure), I wait 5 seconds and call connect() again. This usually works. But sometimes I get a 4010 close code. The docs say 4010 is “Authentication failed” or “Token expired”. My access token is still valid for 20 minutes. I’ve checked the expiration timestamp.
Here’s the relevant bit of the reconnect handler:
socket.on('close', (code, reason) => {
console.log(`Connection closed: ${code} - ${reason}`);
if (code === 4010) {
// Token might be invalid? But it's not expired.
// Should I refresh here?
refreshToken().then(newToken => {
socket = createWebSocket(newToken);
});
} else {
setTimeout(() => reconnect(), 5000);
}
});
If I just reconnect with the same token after a 4010, the server rejects it immediately with another 4010. I have to refresh the token. But refreshing the token on every 4010 feels expensive and wrong. Is 4010 strictly an auth error, or does the server send it when the session state is out of sync? I’ve seen other SDKs just reconnect blindly. The JS Platform SDK handles this internally, but I’m bypassing it for lower latency.
The issue is I can’t distinguish between a “token actually expired” 4010 and a “state mismatch” 4010. The reason string is empty in both cases. I’m currently forcing a token refresh on every 4010. It works, but the token refresh rate spikes during unstable network conditions. Is there a way to check the token validity before refreshing? Or should I just ignore 4010 and retry the connection with the existing token, assuming the server will reject it if it’s truly bad? The current flow is brittle. Need a more solid way to handle this specific close code.