Is anyone else hitting issues with WebSocket reconnection logic for the CXone Notification API in Node.js? I’m building a custom listener, but when I drop the connection and try to reconnect, the ws.on('open') event fires, yet no messages arrive. I’ve verified the token is valid. I’ve tried adding a 5-second delay before reconnecting, but it’s still silent. Here’s the I’m using:
You’re likely hitting a race condition with the subscription handshake. The open event just means the TCP connection is live. The actual subscription to the topic happens asynchronously after that. If you drop the socket before the server confirms the subscription, you lose the state.
Don’t just reconnect. You need to wait for the subscribed event or a specific ack from the server before assuming the stream is active. Also, check if your token is expiring mid-reconnect cycle.
Here’s a safer pattern for the reconnect logic. It tracks the subscription state explicitly.
const WebSocket = require('ws');
const { v4: uuidv4 } = require('uuid');
let ws;
let isSubscribed = false;
const SUBSCRIPTION_ID = uuidv4(); // Keep this consistent
function connect() {
const url = `wss://api.nice-incontact.com/v2/notifications?access_token=${accessToken}`;
ws = new WebSocket(url);
ws.on('open', () => {
console.log('WebSocket connected. Sending subscription...');
// Re-subscribe immediately on open
const subscriptionPayload = {
type: 'subscribe',
subscriptionId: SUBSCRIPTION_ID,
topics: ['/v2/analytics/conversations/details/realtime']
};
ws.send(JSON.stringify(subscriptionPayload));
});
ws.on('message', (data) => {
const msg = JSON.parse(data);
// Handle the ack for the subscription
if (msg.type === 'subscribe' && msg.subscriptionId === SUBSCRIPTION_ID) {
if (msg.success) {
isSubscribed = true;
console.log('Successfully subscribed to topic.');
} else {
console.error('Subscription failed:', msg.message);
ws.close(); // Force reconnect if sub fails
}
return;
}
// Your actual data processing
if (isSubscribed) {
processMessage(msg);
}
});
ws.on('close', () => {
isSubscribed = false;
console.log('Connection closed. Reconnecting in 5s...');
setTimeout(connect, 5000);
});
ws.on('error', (err) => {
console.error('WebSocket error:', err);
});
}
connect();
The key is that isSubscribed flag. Without it, you might process garbage data or miss the initial burst. Also, make sure your token has the view:notifications scope. If it doesn’t, the subscribe call will fail silently or return an error in the message payload.