WebSocket Reconnection Logic for Genesys Cloud Notification API in Node.js

Hey, I’m building a Node.js service to subscribe to the Genesys Cloud Notification API via WebSocket. The connection works fine initially, but I need to handle reconnections properly when the server drops the connection.

I’m using the ws library and following the basic pattern from the docs, but I’m not sure if my reconnection logic is correct. Here’s what I have so far:

const WebSocket = require('ws');

function connectToGenesys(url, token) {
 const ws = new WebSocket(url, {
 headers: {
 Authorization: `Bearer ${token}`
 }
 });

 ws.on('open', () => {
 console.log('Connected to Genesys Cloud Notification API');
 });

 ws.on('message', (data) => {
 console.log('Received:', data.toString());
 });

 ws.on('close', (code, reason) => {
 console.log(`Connection closed with code ${code}: ${reason}`);
 // Reconnect after 5 seconds
 setTimeout(() => connectToGenesys(url, token), 5000);
 });

 ws.on('error', (error) => {
 console.error('WebSocket error:', error);
 });
}

Is this the right approach? The docs mention something about handling close events but don’t give a clear example for Node.js. Also, should I be using exponential backoff instead of a fixed 5-second delay? Any examples or guidance would be appreciated.