0
0
Firebasecloud~7 mins

Firestore trigger functions in Firebase - Commands & Configuration

Choose your learning style9 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.