Node.js WebSocket Notification API reconnection loop causing duplicate events

Trying to stabilize a Node.js listener for the Notification API. The goal is to keep the WebSocket open indefinitely and handle network drops gracefully. I have the initial connection working fine using the ws library. The handshake returns a 101 Switching Protocols, and I start receiving routing:conversation:state events as expected.

The problem is the reconnection logic. When the server closes the connection (clean or dirty), my script attempts to reconnect. It seems to work, but I end up with duplicate event listeners or race conditions where two sockets try to send the same data. Here is the basic structure I am using:

let ws;
function connect() {
 ws = new WebSocket('wss://api.mypurecloud.com/api/v2/analytics/events');
 
 ws.on('open', () => {
 console.log('Connected');
 ws.send(JSON.stringify({
 "apiVersion": "v2",
 "eventTypes": ["routing:conversation:state"]
 }));
 });

 ws.on('message', (data) => {
 handleEvent(JSON.parse(data));
 });

 ws.on('close', (code, reason) => {
 console.log('Disconnected:', code);
 // This is where it gets messy
 if (code !== 1000) {
 setTimeout(connect, 5000);
 }
 });

 ws.on('error', (err) => {
 console.error('WS Error:', err);
 });
}

The issue is that when connect() is called recursively on close, the old ws object might still be holding onto state, or the new connection fires before the old one is fully garbage collected. I am seeing duplicate handleEvent calls for the same conversation update.

I tried adding a flag isConnected to prevent multiple calls, but the WebSocket API is async, so the flag gets set before the actual network connection is established. Is there a standard pattern for this in Node.js? Should I be using a library like reconnecting-websocket or is there a specific way to clean up the previous instance before starting the new one? The documentation doesn’t show much for server-side JS implementations. Just want to make sure I am not leaking memory or double-processing events.