I’m trying to set up some firebase cloud functions. I haven’t been able to get anywhere yet because deploying my functions breaks when I try to import firestore methods.
Here’s my code:
const admin = require('firebase-admin');
admin.initializeApp();
const functions = require("firebase-functions");
const {
//eslint-disable-next-line
getDocs
} = require("firebase/firestore");
// Get all documents from a collection
exports.getAllDocuments = functions.https.onCall(async (data) => {
let collectionName = data.collection;
console.log(collectionName);
});
The getDocs import seems to be the issue here, but I can’t figure out how to fix the problem.
Here’s the error provided:
Function failed on loading user code. This is likely due to a bug in the 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. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.*
In the logger, the messages provided are:
Could not load the function, shutting down
and
Function cannot be initialized. Error: function terminated.
I’ve installed firebase/firestore dependencies with
npm install --save @firebase/firestore
Please note: I’m using firebase v9 so if I can do this with const/require instead of import, that would be ideal. I don’t use getDocs yet in my code but I will in the future. This code snippet has been edited down to help me find the source of the issue.
Thank you!
2
Answers
You are trying to use the web client SDK (firebase/firestore) when you should be using the Firebase Admin SDK. The web client SDK is not really meant for use in nodejs backends like Cloud Functions.
Remove the getDocs import you have now entirely (and uninstall firebase/firestore because you won’t need it for Cloud Functions). Then, review the documentation on using the Firebase Admin SDK to import Firestore APIs and use them. Be sure to use the node.js samples from the documentation (not the web samples).
For your imports, use:
and remove: