I am building a Firebase project where I need to run a cloud function whenever a document is created in a specific Firestore collection. I'm using Node.js with the Firebase Admin SDK and have set up Firebase functions. Everything else is working correctly, but I can't get the function to trigger upon document creation at a specific Firestore path
Here's my code:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccount.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
exports.testFunction = functions.firestore
.onDocumentWritten("Test/{docId}", (change, context) => {
/* ... */
console.log('Written to Test');
});
When I add a new document to the Test collection, the testFunction does not get triggered as expected. I intended for this function to execute and log "Written to Test" each time a document is created in this path.
Could anyone help me understand why this trigger isn't firing and suggest how I might fix this?
You said in the comments that you're running the code you shared as a plain Node.js script, which won't work. Node.js looks for top-level code to execute, so it just runs the admin.initializeApp({...})
and then does nothing else.
To get the onDocumentWritten
to execute and respond to changes in Firestore,, you need to run it in an environment that can execute the Cloud Function. So this can either be the production Cloud Functions environment on Google Cloud or the Firebase emulator for Cloud Functions.