Bird
Raised Fist0
Firebasecloud~7 mins

Firestore trigger functions in Firebase - Commands & Configuration

Choose your learning style10 modes available
Introduction
Firestore trigger functions automatically run backend code when data changes in your Firestore database. They help you react to events like creating, updating, or deleting documents without manual checks.
When you want to send a welcome email right after a user profile is created in Firestore.
When you need to update a summary field whenever related documents change.
When you want to log changes to important data for auditing purposes.
When you want to clean up related data automatically after a document is deleted.
When you want to trigger notifications based on Firestore data changes.
Config File - index.js
index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

// Trigger on document creation in 'users' collection
exports.onUserCreate = functions.firestore
  .document('users/{userId}')
  .onCreate((snap, context) => {
    const newUser = snap.data();
    console.log('New user created:', newUser);
    // Add custom logic here, e.g., send welcome email
    return null;
  });

// Trigger on document update in 'orders' collection
exports.onOrderUpdate = functions.firestore
  .document('orders/{orderId}')
  .onUpdate((change, context) => {
    const before = change.before.data();
    const after = change.after.data();
    console.log('Order updated from', before, 'to', after);
    // Add custom logic here
    return null;
  });

// Trigger on document deletion in 'messages' collection
exports.onMessageDelete = functions.firestore
  .document('messages/{messageId}')
  .onDelete((snap, context) => {
    const deletedMessage = snap.data();
    console.log('Message deleted:', deletedMessage);
    // Add cleanup logic here
    return null;
  });

This file defines three Firestore trigger functions:

  • onUserCreate: Runs when a new document is created in the 'users' collection.
  • onOrderUpdate: Runs when a document is updated in the 'orders' collection.
  • onMessageDelete: Runs when a document is deleted from the 'messages' collection.

Each function logs the event and can be extended with custom backend logic.

Commands
Initialize Firebase Functions in your project to set up the environment for writing trigger functions.
Terminal
firebase init functions
Expected OutputExpected
=== Functions Setup === You're about to initialize a Firebase Functions project. ? What language would you like to use to write Cloud Functions? JavaScript ? Do you want to use ESLint to catch probable bugs and enforce style? Yes ? Do you want to install dependencies with npm now? Yes ✔ Wrote functions/package.json ✔ Wrote functions/index.js ✔ Wrote .eslintrc.js + Firebase initialization complete!
Deploy your Firestore trigger functions to Firebase so they start running on database events.
Terminal
firebase deploy --only functions
Expected OutputExpected
=== Deploying to 'your-project-id'... i deploying functions Running command: npm --prefix "$RESOURCE_DIR" run lint > functions@ lint /workspace/functions > eslint . ✔ functions: Finished running predeploy script. ✔ functions: functions onUserCreate, onOrderUpdate, onMessageDelete deployed successfully ✔ Deploy complete!
→
--only functions - Deploy only the Cloud Functions without affecting other Firebase services.
View logs of your deployed Firestore trigger functions to verify they run correctly when events happen.
Terminal
firebase functions:log
Expected OutputExpected
2024-06-01T12:00:00.000Z onUserCreate: New user created: { name: 'Alice', email: 'alice@example.com' } 2024-06-01T12:05:00.000Z onOrderUpdate: Order updated from { status: 'pending' } to { status: 'shipped' } 2024-06-01T12:10:00.000Z onMessageDelete: Message deleted: { text: 'Hello world' }
Key Concept

If you remember nothing else from this pattern, remember: Firestore trigger functions run your backend code automatically when specific database changes happen.

Common Mistakes
Not returning a promise or null from the trigger function.
Firebase expects a promise or null to know when your function finishes; missing this can cause unexpected behavior or warnings.
Always return null or a promise from your trigger function to signal completion.
Using incorrect Firestore document paths in the trigger definition.
If the path does not match your Firestore structure, the function will never trigger.
Double-check the collection and document path patterns in your trigger to match your Firestore data layout.
Deploying functions without running 'firebase init functions' first.
Without initialization, the functions folder and config files do not exist, so deployment fails.
Run 'firebase init functions' to set up the environment before deploying.
Summary
Initialize Firebase Functions in your project with 'firebase init functions'.
Write Firestore trigger functions in 'index.js' to react to create, update, and delete events.
Deploy your functions using 'firebase deploy --only functions' to activate them.
Use 'firebase functions:log' to check that your functions run correctly when Firestore data changes.

Practice

(1/5)
1. What does a Firestore trigger function do in a Firebase project?
easy
A. Deletes Firestore data without any event
B. Manually updates Firestore data when called
C. Creates a new Firestore database
D. Automatically runs code when data changes in Firestore

Solution

  1. Step 1: Understand Firestore triggers

    Firestore triggers are special functions that run automatically when data changes in Firestore.
  2. Step 2: Identify the trigger's purpose

    They help keep your app reactive by running code on create, update, or delete events without manual calls.
  3. Final Answer:

    Automatically runs code when data changes in Firestore -> Option D
  4. Quick Check:

    Firestore triggers = automatic code run on data change [OK]
Hint: Triggers run code automatically on Firestore data changes [OK]
Common Mistakes:
  • Thinking triggers run manually
  • Confusing triggers with database creation
  • Assuming triggers delete data without events
2. Which of the following is the correct syntax to create a Firestore trigger for document creation in Node.js Firebase Functions?
easy
A. exports.onCreate = functions.firestore.document('users').onCreate((snap, context) => { });
B. exports.onCreate = functions.firestore.document('users/{userId}').onCreate((snap, context) => { });
C. functions.firestore.onCreate('users/{userId}', (snap, context) => { });
D. functions.firestore.document('users/{userId}').create((snap, context) => { });

Solution

  1. Step 1: Recall Firestore trigger syntax

    The correct syntax uses exports, functions.firestore.document(path).onCreate(handler).
  2. Step 2: Match syntax to options

    exports.onCreate = functions.firestore.document('users/{userId}').onCreate((snap, context) => { }); matches this pattern exactly with document path and onCreate event.
  3. Final Answer:

    exports.onCreate = functions.firestore.document('users/{userId}').onCreate((snap, context) => { }); -> Option B
  4. Quick Check:

    Correct Firestore onCreate syntax = exports.onCreate = functions.firestore.document('users/{userId}').onCreate((snap, context) => { }); [OK]
Hint: Use exports with document(path).onCreate(handler) for create triggers [OK]
Common Mistakes:
  • Missing exports keyword
  • Using onCreate directly on firestore without document
  • Wrong method name like create instead of onCreate
3. Given this Firestore trigger function, what will be logged when a document is updated?
exports.logUpdate = functions.firestore.document('posts/{postId}').onUpdate((change, context) => {
  const before = change.before.data();
  const after = change.after.data();
  console.log('Title before:', before.title);
  console.log('Title after:', after.title);
});
medium
A. Logs the title before and after the update
B. Logs only the new title after update
C. Logs only the old title before update
D. Throws an error because change.before is undefined

Solution

  1. Step 1: Understand onUpdate trigger parameters

    The onUpdate trigger receives a change object with before and after snapshots of the document.
  2. Step 2: Analyze the console logs

    The code logs before.title and after.title, so both old and new titles are printed.
  3. Final Answer:

    Logs the title before and after the update -> Option A
  4. Quick Check:

    onUpdate logs before and after data [OK]
Hint: onUpdate provides before and after data snapshots [OK]
Common Mistakes:
  • Assuming only new data is available
  • Thinking change.before is undefined
  • Confusing onUpdate with onCreate
4. Identify the error in this Firestore trigger function code:
exports.deleteUser = functions.firestore.document('users/{userId}').onDelete((snap, context) => {
  const userData = snap.data;
  console.log('Deleted user:', userData.name);
});
medium
A. Missing async keyword for the function
B. onDelete trigger cannot be used on 'users/{userId}' path
C. snap.data should be snap.data() to get document data
D. context parameter is not allowed in onDelete triggers

Solution

  1. Step 1: Check how to access document data

    Firestore document snapshot data is accessed by calling snap.data(), not snap.data property.
  2. Step 2: Identify the error in code

    The code uses snap.data without parentheses, causing undefined userData and runtime error.
  3. Final Answer:

    snap.data should be snap.data() to get document data -> Option C
  4. Quick Check:

    Use snap.data() method to access document data [OK]
Hint: Use snap.data() method, not snap.data property [OK]
Common Mistakes:
  • Using snap.data instead of snap.data()
  • Thinking onDelete can't use context parameter
  • Assuming async is always required
5. You want to create a Firestore trigger that updates a user's profile summary whenever their profile document changes. Which approach correctly ensures the trigger only runs when the 'bio' field changes, avoiding infinite loops?
hard
A. Use onUpdate trigger and compare change.before.data().bio with change.after.data().bio before updating
B. Use onWrite trigger and update the document unconditionally inside the trigger
C. Use onCreate trigger to update bio field after document creation
D. Use onUpdate trigger and update the document without checking any field changes

Solution

  1. Step 1: Choose the right trigger for updates

    onUpdate triggers run on any document update, suitable for detecting changes.
  2. Step 2: Prevent infinite loops by checking field changes

    Compare bio field before and after update; only proceed if bio changed to avoid recursive updates.
  3. Final Answer:

    Use onUpdate trigger and compare change.before.data().bio with change.after.data().bio before updating -> Option A
  4. Quick Check:

    Check field changes in onUpdate to avoid loops [OK]
Hint: Compare before and after fields in onUpdate to avoid loops [OK]
Common Mistakes:
  • Using onWrite and updating unconditionally causing loops
  • Using onCreate which triggers only once
  • Not checking field changes before updating
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard