HiAlex Thompson
To guarantee a clean handshake using new tokens, we recommend rebuilding a fully underlying MSSQL connection pool example, not just calling. close()
. This means removing and reinstalling all cashed states:
async function getConnection() {
const token = await getAccessToken();
const shouldRefreshConnection =
!connectionPool ||
!connectionPool.connected ||
Date.now() >= tokenExpiresAt - 5 * 60 * 1000;
if (shouldRefreshConnection) {
if (connectionPool) {
try {
await connectionPool.close();
} catch (err) {
console.warn('Error closing connection pool:', err.message);
}
connectionPool = null; // Force reinitialization
}
connectionPool = await mssql.connect({
server: sqlServer,
database: database,
authentication: {
type: 'azure-active-directory-access-token',
options: { token },
},
options: {
encrypt: true,
trustServerCertificate: false,
connectionTimeout: 15000,
},
});
}
return connectionPool;
}
If this answer was helpful and pointed you in the right direction, please consider clicking "Accept Answer"—it may benefit other community members reading this thread. If you have any further questions, feel free to let us know.