0
0
FirebaseHow-ToBeginner · 3 min read

How to Trigger a Function on Firestore Write Events

Use functions.firestore.document('path').onWrite() to trigger a Firebase Cloud Function whenever a Firestore document is created, updated, or deleted. This function runs automatically on any write event at the specified document path.
📐

Syntax

The onWrite() function listens to all write events (create, update, delete) on a Firestore document. You specify the document path inside document('path'). The function receives a change object with before and after states of the document.

  • functions.firestore.document('path'): Selects the Firestore document to watch.
  • .onWrite((change, context) => { ... }): Defines the function triggered on any write.
  • change.before: Document state before the write.
  • change.after: Document state after the write.
  • context: Metadata about the event.
javascript
const functions = require('firebase-functions');

exports.myFunction = functions.firestore.document('collection/{docId}').onWrite((change, context) => {
  // Your code here
  return null;
});
💻

Example

This example triggers a function whenever a document in the users collection is created, updated, or deleted. It logs the type of change and the document ID.

javascript
const functions = require('firebase-functions');

exports.logUserChange = functions.firestore.document('users/{userId}').onWrite((change, context) => {
  const beforeData = change.before.exists ? change.before.data() : null;
  const afterData = change.after.exists ? change.after.data() : null;
  const userId = context.params.userId;

  if (!beforeData && afterData) {
    console.log(`User ${userId} created with data:`, afterData);
  } else if (beforeData && afterData) {
    console.log(`User ${userId} updated from`, beforeData, 'to', afterData);
  } else if (beforeData && !afterData) {
    console.log(`User ${userId} deleted. Previous data:`, beforeData);
  }
  return null;
});
Output
User 123 created with data: {name: 'Alice', age: 30} User 123 updated from {name: 'Alice', age: 30} to {name: 'Alice', age: 31} User 123 deleted. Previous data: {name: 'Alice', age: 31}
⚠️

Common Pitfalls

  • Not returning a promise or null from the function can cause unexpected behavior.
  • Using onUpdate() or onCreate() when you want to catch all write types.
  • Incorrect document path syntax, missing wildcards like {docId}.
  • Not checking if change.before.exists or change.after.exists leads to errors when documents are created or deleted.
javascript
/* Wrong: Missing return and no checks for document existence */
exports.badFunction = functions.firestore.document('items/{id}').onWrite((change, context) => {
  console.log(change.before.data()); // Error if document was created
  console.log(change.after.data());
});

/* Right: Return null and check existence */
exports.goodFunction = functions.firestore.document('items/{id}').onWrite((change, context) => {
  if (!change.before.exists) {
    console.log('Document created:', change.after.data());
  } else if (!change.after.exists) {
    console.log('Document deleted:', change.before.data());
  } else {
    console.log('Document updated:', change.after.data());
  }
  return null;
});
📊

Quick Reference

Use this quick guide to remember how to trigger functions on Firestore writes:

ActionFunction to UseDescription
Trigger on any writeonWrite()Runs on create, update, or delete of a document
Trigger on create onlyonCreate()Runs only when a document is created
Trigger on update onlyonUpdate()Runs only when a document is updated
Trigger on delete onlyonDelete()Runs only when a document is deleted
Document pathdocument('collection/{docId}')Use wildcards to match any document ID

Key Takeaways

Use functions.firestore.document('path').onWrite() to trigger on all Firestore writes.
Check change.before.exists and change.after.exists to detect create, update, or delete.
Always return null or a promise from your Cloud Function to signal completion.
Use wildcards like {docId} in document paths to handle multiple documents.
Choose onCreate, onUpdate, or onDelete if you want to trigger only specific write types.