Search code examples
firebasegoogle-cloud-functionsfirebase-admin

How do I switch to another serviceAccountKey.json via .firebaserc on Firebase Cloud Functions?


In my .firebaserc file, I provided two Firebase databases, one for dev and one for production:

{
  "projects": {
    "default": "db-dev",
    "production": "db-prod"
  }
}

So when I'm deploying to production, I'll just run:

firebase use production
firebase deploy --only functions

My problem is I'm also using cloud storage in one of my cloud functions, so I have two different serviceAccountKey.json files that I will use here:

const gcs = require('@google-cloud/storage')({ keyFilename: 'serviceAccountKey.json' })

My question is how do I automatically switch to another serviceAccountKey.json when I switch to another database via firebase use?


Solution

  • Each Firebase project will have its own Environment Configuration. The solution is to store the service account keys there.

    Set the service account key for each Firebase project:

    firebase use default
    firebase functions:config:set admin.key="serviceAccountKey-dev.json"
    
    firebase use production
    firebase functions:config:set admin.key="serviceAccountKey-prod.json" 
    

    The environment configuration will be available via functions.config():

    const functions = require('firebase-functions')
    const gcs = require('@google-cloud/storage')({ 
      keyFilename: functions.config().admin.key 
    })