Error: Could not load the default credentials (Firebase function to firestore)

@aldobaie's answer helped me figure out what was going on for my use case. For those who are not looking to add async/await to all their calls, remember that the firestore calls return promises, so prepending them with return has the same effect.

In my case:

function doSomething(...) {
    return admin.firestore().collection(...).doc(...).get()
        .then((doc) => {...})
        .catch(err => {...})

module.exports = functions.firestore.document('collection/{docId}').onWrite((change, context) => {
    return doSomething()

I think the accepted answer goes against Firebase's recommend configuration. The function environment has access to admin credentials already, and passing your key in the code is not recommended.

I do it like this:

const functions = require('firebase-functions')
const admin = require('firebase-admin')

I had the same error "Could not load the default credentials".

The error occured after updating my project dependencies with npm update. More precisely firebase-admin and firebase-functions.

Before update:

"dependencies": {
    "@google-cloud/firestore": "^1.3.0",
    "firebase-admin": "~7.0.0",
    "firebase-functions": "^2.2.0"

After update:

"dependencies": {
    "@google-cloud/firestore": "^1.3.0",
    "firebase-admin": "^8.6.0",
    "firebase-functions": "^3.3.0"

I added the serviceAccountKey.json to my project and changed the imports with the code provided at the service account setting of my firebase project.

From :

var admin = require('firebase-admin')



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

  credential: admin.credential.cert(serviceAccount),
  databaseURL: ''

See @Fernando Rocha's answer below to access the account setting of your firebase project.

What I first did to solve it was add my firebase admin sdk key to my project.

I downloaded it at**YOUR_PROJECT_ID**/settings/serviceaccounts/adminsdk

Admin SDK Key Download Page

then at admin.initializeApp(); I changed to:

    credential: admin.credential.cert(require('../keys/admin.json'))

My folder structure is

├── key
│   ├── admin.json
├── src
│   ├── index.ts

HOWEVER, a better practice and safer approach, as some mentioned already: You could use environment variables to store your credentials, this way you won't commit it to a repository such as Github, keep it safer from safety breaches and won´t make it hardcoded.

Depending on your project and where you'll deploy it there's a different way to do it.

There are many tutorials around on how to create and access env variables (like this one), but you could use a name it like the example below: