Triggering Firebase Cloud Functions on Firestore Writes: How to Configure, Deploy, and Avoid Common Pitfalls
Learn how to set up a Firestore‑triggered Cloud Function, understand its limits, and avoid the most common mistakes that can cause infinite loops or hanging deployments. Includes a working code sample, deployment steps, and verification tips.
27 Feb 2026, 08:49 UTC

What You Can Do With Firestore Triggers
When a document in a Firestore collection is created, updated, or deleted, you can automatically run server‑side code. This is handy for tasks like sending welcome e‑mails, updating aggregated stats, or enforcing data integrity. The key steps are:
- Export a named function that listens on a Firestore path.
- Deploy the function to Firebase.
- Verify that the function fires when you write to the collection.
Define the Trigger in Code
Below is a minimal example that runs when a user document is added to the users collection. The function logs the new user data and returns null to signal completion.
// functions/index.js
const functions = require('firebase-functions');
exports.onUserCreate = functions.firestore
.document('users/{userId}')
.onCreate((snap, context) => {
const data = snap.data();
console.log('New user created:', data);
// Perform any async work here, e.g. send email
return null; // Required to signal completion
});
Explanation of key parts:
functions.firestore.document('users/{userId}')– watches any document underusers..onCreate()– triggers only on creation. Use.onUpdate()or.onDelete()for other events.snap– aDocumentSnapshotrepresenting the new document.- Return
null(or a promise) to let Cloud Functions know the work is finished.
Deploying the Function
Ensure your package.json lists firebase-functions as a dependency. Then deploy only the functions sub‑project:
# Run from the root of your Firebase project
firebase deploy --only functions
Permissions required: you must have the functions.deployer role in the Firebase project. If the deployment fails with “missing dependency”, add firebase-functions to dependencies and run npm install again.
Testing the Trigger
After deployment, create a document in the users collection via the Firebase console or SDK. The Cloud Functions logs should show the console output. To inspect logs:
- Open the Firebase console → Functions →
onUserCreate. - Click View logs.
- Look for the
New user created:message.
Alternatively, use the Firestore emulator for local testing:
# Start emulators
firebase emulators:start --only functions,firestore
# In a separate terminal, write a document
firebase functions:shell
# Inside the shell, trigger the function manually
onUserCreate({data: {name: 'Alice', email: '[contact removed]'}})
Runtime Limits and Cost Considerations
- Timeout – The default Node 18 runtime allows a maximum of 540 seconds (9 minutes). If your function may run longer, set
timeoutSecondsinfunctions.runWith(). - Concurrent instances – A project can run up to 2000 concurrent Cloud Function instances. Exceeding this cap throttles new invocations.
- Firestore ops – Each read, write, or delete inside the function counts toward Firestore billable operations. Heavy loops can inflate costs.
- Cold starts – After 30 minutes of inactivity, a new instance may take 1–2 seconds to start. For low‑latency needs, consider
onCallor HTTP functions.
Common Mistakes and How to Avoid Them
- Not returning a promise or null – The runtime waits for the returned value to resolve. Without it, the function hangs and may time out.
- Missing firebase-functions dependency – Deployment fails with “cannot find module ‘firebase-functions’”. Add it to
dependencies. - Infinite loop by writing back to the same collection – If the function writes to
users, it re‑fires. Guard with a flag field or write to a separate collection. - High‑frequency triggers without throttling – Rapid writes can spike invocation counts. Use
functions.runWith({memory: '2GB', timeoutSeconds: 540})to increase resources, but monitor logs for patterns. - Using onUpdate without checking what changed –
onUpdatereceiveschange.beforeandchange.after. Compare fields to act only on relevant changes.
Practical Verification Checklist
- Deploy function and confirm no deployment errors.
- Write a test document and watch the Cloud Functions logs for the expected console output.
- Verify the invocation count and average duration in the Functions dashboard.
- Check that no errors or timeouts appear. If you see a timeout, increase
timeoutSecondsor refactor your code. - Confirm billing: in the Firestore usage tab, the function’s reads/writes should be reflected.
When to Use Firestore Triggers vs. onCall
Use a Firestore trigger when the action should happen automatically in response to data changes, regardless of who performed the write. Use onCall when you need a low‑latency, client‑initiated operation that may read or write data but should not fire for every write in the collection.
Summary
Setting up a Firestore‑triggered Cloud Function is straightforward: export a function with .onCreate(), .onUpdate(), or .onDelete(), deploy, and test. Keep an eye on runtime limits and guard against infinite loops. With these practices, you can reliably automate backend logic in response to Firestore changes.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.