Mayor
Mayor

Reputation: 333

Is firebase sevices.json needed for admin SDK on cloud functions

I am trying to write a function that writes to a different database when a user writes to the default database , I did my research and i am a little bit confused

I saw this on firebase

var admin = require('firebase-admin');

var serviceAccount = 
require('path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
databaseURL: 
'https://<DATABASE_NAME>.firebaseio.com'
});

And also this

const app1 = firebase.initializeApp({
databaseURL: "https://testapp-1234-1.firebaseio.com"
});

const app2 = firebase.initializeApp({
databaseURL: "https://testapp-1234-2.firebaseio.com"
 }, 'app2');

 // Get the default database instance for an app1
 var database1 = firebase.database();

// Get a database instance for app2
var database1 = firebase.database(app2);

So my question is do we need the service.json file which holds the secret key when using cloud functions admin SDK

Upvotes: 6

Views: 644

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

For almost all typical use cases, you don't need to provide a service account when working with the Firebase Admin SDK in Cloud Functions. This is because Cloud Functions provides the credentials for the default service account in the project where the function is deployed. (This account can be seen as the App Engine default service account in the Cloud console.)

It's strongly recommended to initialize the Admin SDK with no arguments and accept this default account:

const admin = require('firebase-admin');
admin.initializeApp();   // accept the default service account

As part of taking this default, the Admin SDK will also understand the URL of your default Realtime Database shard, and the URL of your default Cloud Storage bucket. You won't need to provide these values. As such, your code will be much more easy to port to other projects.

If you need to access non-default resources of your project, you can also initialize other instances of firebase-admin to point to those that you explicitly configure. This is what your second code sample is illustrating. If you don't have any non-default resources to access, then don't bother with this.

If there is something that the service account can do, you can grant that role in the Cloud console. The one notable action that this account currently can't perform by default is cryptographic signing of blobs. In practical terms, this means it can't generate signed URLs for object stored in Cloud Storage. This is a fairly common thing to do in Cloud Functions. To remedy this, you need to grant the signBlob role to the default service account.

Upvotes: 6

Related Questions