Node.js WebSocket reconnection logic failing for Genesys Notification API

Need some help troubleshooting my reconnection loop. The initial connect works fine, but after a network blip the onclose handler fires and the reconnect attempt throws a WebSocket is already in CLOSING or CLOSED state error before the new socket even opens.

i’ve tried adding a 500ms delay and checking ws.readyState before calling new WebSocket(), but it still crashes the process. is there a specific cleanup step i’m missing between closing and reopening the connection to /api/v2/analytics/events?

ws.on('close', () => {
 console.log('Connection closed. Reconnecting...');
 setTimeout(() => {
 if (ws.readyState === WebSocket.CLOSED) {
 connect(); // crashes here
 }
 }, 500);
});