Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase error: Function failed on loading user code (node.js)

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

like image 692
Suraj Avatar asked Jul 10 '20 22:07

Suraj


1 Answers

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();
like image 134
Krozi Avatar answered Oct 01 '22 16:10

Krozi