1

I am making external API calls in my Firebase Cloud Functions in which I need to pass an authentication token. Instead of generating a new authentication token every time I need to make the external API call, I store the API token when I don't have one, and as long as it's valid, I want to re-use it for further requests.

I have created a global variable globalToken for this purpose. However, when I call my function to retrieve a token and re-use if possible, an existing token is never re-used as the function always seems to say that the global variable is set to null.

let globalToken = null

async function getToken() {
    if(!!globalToken) {
        console.log('was able to re-use already-existing token')
        return globalToken
    }
    console.log(`no existing token could have been reused because globalToken was set to: ${globalToken}`) // always displays globalToken as null
    const newToken = axios.post(...)
    globalToken = newToken
    console.log(`updated globalToken to: ${globalToken}`) // correctly prints out the new token
    return newToken
}

exports.getToken = functions.https.onCall(async (data, context) => {
    const token = await getToken()
    return ({ token: token })
})

If the logs confirm that the global variable is being changed at the time of new token retrieval, why do the subsequent runs read the global variable as null value instead of the already-retrieved token?

Sam
  • 1,130
  • 12
  • 36
  • I see no other reads of `globalToken` except the `console.log`, but most likely your other code is reading `globalToken` before you set it. Only if the code is guarded by an `await` call or ` `then()` clause will it be waiting for the data that is asynchronously loading. Also see https://stackoverflow.com/questions/40688268/why-does-firebase-lose-reference-outside-the-once-function/40688890#40688890 – Frank van Puffelen Apr 22 '22 at 23:36
  • It's not. When I say that `globalToken` is read as `null`, it's because the log statement outputs it as that - not because some other function not listed in my post retrieves it as null. – Sam Apr 23 '22 at 11:01
  • 2
    Thanks for clarifying. It's a bit unclear from the code you shared, but I expect you also need to `await` the result when you call `axios.post(...)`. – Frank van Puffelen Apr 23 '22 at 14:13

0 Answers0