How to properly call Key Vault's async getSecret(secretName) method at the top level of a CommonJS module?

Wang, Qinjie 65 Reputation points
2025-06-18T11:51:07.21+00:00

I want call Key Vault async getSecret(secretName) method get secret into config setting. but its async function , cant run in CommonJS module before init function, Could you please suggest how I might improve this section?
Image

Azure Key Vault
Azure Key Vault
An Azure service that is used to manage and protect cryptographic keys and other secrets used by cloud apps and services.
1,448 questions
0 comments No comments
{count} votes

Accepted answer
  1. Alex Burlachenko 9,780 Reputation points
    2025-06-19T07:56:03.17+00:00

    Wang, Qinjie hi there )))

    thanks for posting this question, its a common hiccup when working with async stuff at the top level in commonjs ::) u can wrap the async call in an immediately invoked function expression (iife)

    const config = require('./config');
    let secretValue;
    
    (async () => {
        try {
            secretValue = await getSecretValue();
            config.microsoftAppPassword = secretValue;
        } catch (err) {
            console.error('oops, failed to fetch secret', err);
        }
    })();
    
    

    this way, the async operation runs right away, and u can still access the config values later.

    also, if u're using node 14 or later, u might wanna explore top level await by switching to es modules. just rename ur file to .mjs or add "type": "module" in package.json. but yeah, commonjs needs this little workaround ))

    u could move the secret fetching logic into a separate initialization function that runs before the bot starts. this keeps things clean and avoids race conditions.

    actually JS too :))))))

    async function initConfig() {
        config.microsoftAppPassword = await getSecretValue();
    }
    
    initConfig().then(() => {
        // start ur bot here
    });
    
    

    this might help in other tools too, not just azure. worth looking into how other frameworks handle async config loading, aha u know )

    if u're feeling fancy, u could even use a config loader library like 'dotenv' for local dev and key vault for production. hybrid approaches save lives sometimes :))

    ps: microsoft's key vault docs have a ton of examples on async/await patterns peek here for more. happy coding ;D

    rgds,

    Alex

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.