Node.js WebSocket Notification API reconnecting with stale token after 401

Docs state: “The WebSocket connection remains open for the lifetime of the access token. If the token expires, the server closes the connection.” I’m building a Node.js service to consume Notification API events. The initial handshake works fine with a fresh bearer token.

The problem is the reconnection logic. When the server drops the connection (usually after an hour), my code fetches a new token via the client credentials grant and attempts to reconnect. The new connection immediately gets a 401 Unauthorized frame.

Here is the reconnect handler:

ws.on('close', async (code, reason) => {
 console.log('Connection closed:', code);
 const newToken = await getNewAccessToken();
 console.log('Retrying with new token...');
 const newWs = new WebSocket(`${endpoint}?token=${newToken}`);
 // ... attach handlers
});

The token looks valid in Postman. I’ve verified the scope includes websockets. The server logs show the connection attempt but reject it instantly. It feels like the server is caching the session state from the previous closed socket.

Is there a specific header or query param needed to signal a fresh session? Or should I be waiting for a specific close code before requesting a new token? The docs don’t specify a cooldown period.

The error payload is just "message": "Unauthorized". No trace ID.