Cod3Flu3nc3
Cod3Flu3nc3

Reputation: 147

Firebase cloud function server side global variables

It's possible to have a sort of a global variable on firebase cloud functions?

I mean I could have an index.js like that in which set-up a global variable, let's say panicModeVariable.

And I would like to check in my cloud functions this variable before doing anything, like here in the auth create user trigger.

const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

var globalVariable = false;

// Create Account User
exports.createUserAccount = functions.auth.user().onCreate(event => {
    if (!globalVariable) {
        const uid = event.data.uid
        const email = event.data.email
        const photoUrl = event.data.photoURL
    }
    [...]

I tried with two dummy functions

exports.setGlobal = functions.https.onRequest((request, response) => {
    globalVariable = true;
    response.send("Set " + globalVariable);
});

exports.getGlobal = functions.https.onRequest((request, response) => {
    response.send("Read " + globalVariable);
});

But it seems that I cannot access this variable in the way I intended.

The writing function it uses a 'local' variable, while the reading one uses the initial value, always.

I'd like to do that, if it is possible, to have a sort of server side variable to be read directly without the need to a call to the SDK to read, let's say, a database stored value (so that to not have a function call counting).

Upvotes: 5

Views: 5640

Answers (1)

sketchthat
sketchthat

Reputation: 2688

You could use Environment Config variables https://firebase.google.com/docs/functions/config-env

As far as I'm aware, you can't set them in the function themselves, they need to be set by CLI before you upload a function.

You could do something like firebase functions:config:set panic.mode=true

Then in your createUserAccount function you could call functions.config().panic.mode

But this won't help you set the variable via the https trigger. For that you'll need to make use of the database.

Upvotes: 2

Related Questions