/firebase-tutorials

How to use Firestore triggers in Firebase functions?

Learn to use Firestore triggers in Firebase Functions. Our step-by-step guide covers project setup, CLI installation, function creation, and deployment.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to use Firestore triggers in Firebase functions?

 
Step 1: Set Up Firebase Project

To use Firestore triggers in Firebase functions, you need to set up a Firebase project. Follow these steps:

  • Go to the Firebase Console.
  • Click on "Add project" and follow the prompts to create a new project or select an existing project.
  • Enable Firestore by navigating to "Build" > "Firestore Database" and choose "Create database". Select "Start in Test Mode" or "Start in Production Mode" as per your need.

 
Step 2: Install Firebase CLI

You will need the Firebase CLI to deploy your functions. Install it if you haven't already:

npm install -g firebase-tools

 
Step 3: Initialize Firebase Functions

Run the following command to initialize Firebase Functions in your project directory:

firebase init functions
  • Choose your Firebase project when prompted.
  • Select JavaScript or TypeScript as your language preference.
  • Choose to install the dependencies when asked.

 
Step 4: Define Firestore Trigger Function

Open the functions/index.js file (or functions/src/index.ts for TypeScript) and define a Firestore trigger like this:

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

exports.onDocumentCreate = functions.firestore
  .document('/collectionName/{documentId}')
  .onCreate((snap, context) => {
    const newValue = snap.data();

    // Perform desired operations on newValue
    console.log('New document created:', newValue);

    return null;
  });

Replace /collectionName/{documentId} with the path of the document you want to watch.

 
Step 5: Add Firestore Trigger Logic

Depending on your use case, you can add logic to the trigger function. For example, you might want to send a notification or update another document. Here's an example of sending a message when a document is created:

exports.onDocumentCreate = functions.firestore
  .document('/collectionName/{documentId}')
  .onCreate((snap, context) => {
    const newValue = snap.data();
    
    // Example logic: Log a message when a new document is created
    const message = `A new document with ID ${context.params.documentId} was created.`;
    console.log(message);

    // Return null or a Promise
    return null;
  });

 
Step 6: Deploy Firebase Functions

Run the following command to deploy your function:

firebase deploy --only functions

This command will deploy your function to Firebase, and it will start executing when a document is created in the specified Firestore collection.

 
Step 7: Test the Firestore Trigger

To test your Firestore trigger, add a new document to the specified collection in Firestore. You can do this manually through the Firebase Console or use a script to add data. Check the Firebase Functions logs to verify if your trigger executed successfully:

firebase functions:log

This command will show you the logs from your function execution, and you can see the output from your console.log statements.

 
Step 8: Modify Firestore Trigger for Other Operations

You can create triggers for other operations like update, delete, and write (any operation). Here's an example for an update trigger:

exports.onDocumentUpdate = functions.firestore
  .document('/collectionName/{documentId}')
  .onUpdate((change, context) => {
    const newValue = change.after.data();
    const previousValue = change.before.data();

    // Compare values, perform operations
    console.log('Document updated:', newValue, 'Previous Value:', previousValue);

    return null;
  });

Modify /collectionName/{documentId} and adapt the logic to fit your use case.

 
Conclusion:

By following these steps, you have set up and deployed Firestore triggers in Firebase functions. These triggers allow you to automate backend operations in response to changes in your Firestore database. Remember to adapt the code examples to your specific project requirements.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022