29

I am a relative noob with Firebase my first time using it and following along with a tutorial. The tutorial is a bit outdated and I have been fixing bugs as I have been going, but this one has got me completely stuck. I try to run a different functions that trigger when a document is created in certain collections. However, i get the following error:

Error

!  functions[createNotificationOnlike(us-central1)]: Deployment error.
Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs

There are 3 more identical errors that correspond to the other exports in the following index.js file.

Index.js

exports.createNotificationOnlike = functions.firestore.document('likes/{id}').onCreate(async (snapshot) => {
    try {
        const doc = await db.doc(`posts/${snapshot.data().postId}`).get(); // we have access to user handle via the likes route
        if(doc.exists){
            await db.doc(`notifications/${snapshot.id}`).set({ // the id of the like is the same as the id of the notification that pertains to the like
                createdAt: new Date().toISOString,
                recipient: doc.data.userHandle,
                sender: snapshot.data().userHandle,
                type: 'like',
                read: false,
                postId: doc.id
            });
            return;
        }    
    } catch (err) {
        console.error(err);
        return;
    }
});

exports.removeNotificationOnUnlikePost = functions.firestore.document('likes/{id}').onDelete( async (snapshot) => {
    try {
        await db.doc(`notifications/${snapshot.id}`).delete();
        return;   
    } catch (err) {
        console.error(err);
        return;
    }
})

exports.createNotificationForComments = functions.firestore.document('comments/{id}').onCreate(async (snapshot) => {
    try {
        const doc = await db.doc(`posts/${snapshot.data().postId}`).get();
        if(doc.exists){
            db.doc(`notifications/${snapshot.id}`).set({
                createdAt: new Date().toISOString,
                recipient: doc.data.userHandle,
                sender: snapshot.data().userHandle,
                type: 'comment',
                read: false,
                postId: doc.id
            })
            return;
        }
    } catch (err) {
        console.error(err);
        return; // we dont need return messages since this isnt an endpoint it is a db trigger event
    }
})

// auto turn the app into base route url/api
exports.api = functions.https.onRequest(app);

I have checked the logs as suggested by the error and i get the following messages which i think are useless, there are three other identical errors for the other functions

Error Logs

removeNotificationOnUnlikePost
{"@type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs"}

Here is my package.json file

Package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "10"
  },
  "dependencies": {
    "busboy": "^0.3.1",
    "express": "^4.17.1",
    "firebase": "^7.16.0",
    "firebase-admin": "^8.10.0",
    "firebase-functions": "^3.6.1"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}

Lastly, here is my config stuff that was used to initialize everything:

admin.js

const admin = require('firebase-admin');
var serviceAccount = require('../../service-acct/socialapp-e5130-firebase-adminsdk-uo6p6-5495e18b97.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    storageBucket: "socialapp-e5130.appspot.com",
    databaseURL: "https://socialapp-e5130.firebaseio.com"
});

const db = admin.firestore();

module.exports = { db, admin }

Firebase init

const firebase = require('firebase');
const config  = require('../util/config.js');
firebase.initializeApp(config);

P.S. It is worth mentioning that the http.onRequest trigger (api) was actually working and I have been developing without deploying using firebase serve. Now that I am ready to deploy these triggers something is going heinously wrong. Any help is greatly appreciated

1

9 Answers 9

58

Enter this command for getting log:

firebase functions:log
Sign up to request clarification or add additional context in comments.

6 Comments

Why isnt this enabled by default! Thanks for the tip.
This worked for me. Was missing a dependency in the package.json file
Thanks, worked for me, it turned out that myServiceAccount.json file was on the wrong path
I have related error with gloud. Local logs was more helpful than web ones. command: gcloud functions logs read
Yes, should absolutely be enabled by default
|
15

I had the exact same problem, trying to deploy the exact same code as you and I was just able to get it to deploy properly.

If yours is the same issue as mine, this is where the problem is:

var serviceAccount = require('../../service-acct/socialapp-e5130-firebase-adminsdk-uo6p6-5495e18b97.json');

It looks like when deploying to firebase you cant have code trying to reach outside your project folder, so the solution would be to have the key inside which isn't recommended or to set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of your service account key json file as explained in https://firebase.google.com/docs/admin/setup#windows and then just having

admin.initializeApp();

1 Comment

Thank you, it works, And also need to remove all require("firebase-admin"), should use import
7

I had the same issue while setting up SendGrid.

I got this error because I accidentally installed SendGrid to the root folder instead of the functions folder.

Make sure to install your service to your functions folder using the cmd prompt. It should look something like this:

D:\firebaseProject\functions> npm i @sendgrid/mail

2 Comments

This was the problem for me - thanks for pointing this out!
Thank you this worked. I have exact same problem with sendgrid.
3

I had this error once and I fixed it by checking my code again, check maybe you require or import a dependency or module that you have not installed and try to check your package.json file make sure you installed all the necessary module and dependencies.

But mostly the problem is due to importing a module you did not install or there is a bug in your code.

2 Comments

This hint really helped me a lot.
Good hint. Is there a reason this can't be debugged in the log? You just have to guess around for a while?
2

in my case i had a file starting with capital case letter, but require(...) with a lower case letter, it worked on Mac because it ignores it, as i understand, but deploying these functions results in this error.

Renaming file to lower case fixed this error for me.

Comments

1

Mine was because I tried to import a module that dependents that is not standard-alone

const axioms = require("axioms");

I solved it by adding the module name version to dependencies list in the package.json file.

"dependencies": {
    ....
    "axios": "^0.27.2"
}

I got the module version with this command

npm view axios version

Comments

1

I had this same problem. check if your package.json file has all the dependencies that you used to write firebase functions.

e.g. I had written a firebase function in which I called nodemailer dependancy but did not installed in package.json file of 'functions' directory

Note: Remember to install required packages in 'functions' directory only

Comments

0

With the suggestion of the recommended answer I moved all my cloud functions code to the single index.js file (rather than 'require' statements) and it seemed to work for me. Note that I omitted any API keys and such and it still worked. I am assuming that since this deployment is handled by the firebase CLI it already knows this is a trusted environment.

Comments

0

Another way to view deployment-time logs is to go to the Logs Explorer in the Google Cloud Console.

If you're not familiar with Google Cloud console, maybe because you're only familiar with the Firebase console that's a simplified version of the Google Cloud console, then check out these docs for how to access the Logs Explorer on Google Cloud Console.

In my case, I had to access the logs from the Logs Explorer because when I ran firebase functions:log as suggested by Chinmay Atrawalkar, I got the error Error: Failed to list log entries Failed to retrieve log entries from Google Cloud..

Through the Logs Explorer, I could see the following error: Detailed stack trace: Error: Cannot find module 'file-saver'. From there I was able to figure out I just needed to add file-saver to my functions/package.json dependencies by running yarn add file-saver from my functions directory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.