Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include the Google Cloud's JSON Project Key file in a Google Cloud Function?

I have a Google Cloud Function that works well and I want, once executed before the callback, to connect to Firestore to add a document to my Notifications collection.

const Firestore = require('@google-cloud/firestore');

const firestore = new Firestore({
  projectId: 'my-firebase-project',
  keyFilename: 'thekey.json',
});

var fsDocument = {
    'username': 'theuser',
    'organization': 'theorg',
    'attr': [
        {k:'key1', v:'val1'},
        {k:'key2', v:'val2'}
    ]
};

firestore.collection('Notifications').add(fsDocument).then(documentReference => {
    console.log('Added document with name' + documentReference.id);
});

How can I include the key file to my google cloud function? So far, I am creating them in console.cloud.google.com.

like image 594
Lazhar Avatar asked Oct 21 '25 11:10

Lazhar


1 Answers

All files in your functions directory will be sent to Cloud Functions when you deploy. You could put your credentials in a file under functions, then refer to it with a relative path like this:

const firestore = new Firestore({
  projectId: 'my-firebase-project',
  keyFilename: './thekey.json',
});

You should only do this if your credentials are for a project different from the one running your Cloud Function. If you're trying to access Firestore in the same project as the one running your function, just use the default credentials using the Admin SDK. There are lots of examples of this in functions-samples.

like image 99
Doug Stevenson Avatar answered Oct 23 '25 03:10

Doug Stevenson