Firebase

How to trigger Firebase Cloud Functions on Firestore document changes?

Discover the simple steps to activate Firebase Cloud Functions with Firestore document changes. This guide breaks down how to set up and keep an eye on database events smoothly. Perfect for efficient and hassle-free monitoring.

Developer profile skeleton
a developer thinking

Overview

Using Firestore triggers, Firebase Cloud Functions can spring into action when Firestore documents are created, updated, or deleted. These serverless functions let you automate backend tasks immediately. They execute custom logic right when specific changes happen in your Firestore database and do it all without endless client-side polling. This feature is a game changer for data validation, sending real-time notifications, and updating aggregated data. It keeps your app nimble and efficient—no constant monitoring needed.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to trigger Firebase Cloud Functions on Firestore document changes?

Step 1: Set up a Firebase Project

  1. Head over to the Firebase Console.
  2. Click "Add Project" and just follow the setup instructions.
  3. Once your project is up and running, add Firestore by going to the Firestore section in the Firebase Console and clicking "Create Database".

Step 2: Install Firebase CLI

  1. Make sure Node.js and npm are installed on your machine.
  2. Install the Firebase CLI with this command:
    ```sh
    npm install -g firebase-tools
    ```
  3. Log in to Firebase using the CLI:
    ```sh
    firebase login
    ```

Step 3: Initialize Firebase Functions in Your Project

  1. Create a new directory for your Firebase project and navigate into it:
    ```sh
    mkdir my-firebase-project
    cd my-firebase-project
    ```
  2. Initialize Firebase in your project:
    ```sh
    firebase init
    ```
  3. During the setup, select "Functions" and then choose the Firestore project. Follow the prompts to set up Functions and Firestore.

Step 4: Write a Cloud Function to Trigger on Firestore Document Changes

  1. Open the index.js file in the functions directory.

  2. Add this code to create a function that triggers on Firestore document changes:
    ```javascript
    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();

    exports.onDocumentUpdate = functions.firestore
    .document('your-collection/{docId}')
    .onWrite((change, context) => {
    // Get the before and after snapshots
    const beforeSnapshot = change.before.exists ? change.before.data() : null;
    const afterSnapshot = change.after.exists ? change.after.data() : null;

    console.log("Document updated:", context.params.docId);
    console.log("Before:", beforeSnapshot);
    console.log("After:", afterSnapshot);

    // Perform your custom logic here

    return null;
    });
    ```

Step 5: Deploy the Cloud Function

  1. Deploy your Cloud Functions to Firebase:
    ```sh
    firebase deploy --only functions
    ```
  2. Wait for the deployment process to complete. The CLI will give you a confirmation and details of the new function URLs.

Step 6: Test Your Cloud Function

  1. Open your Firestore database from the Firebase Console.
  2. Navigate to the collection specified in your function (your-collection).
  3. Add a new document or update an existing document in the collection.
  4. Check the Firebase Console logs:
    ```sh
    firebase functions:log
    ```
  5. Verify that the function triggers and logs the before and after states of the document.

Step 7: Customize Your Function (Optional)

  1. Modify the function logic to perform specific tasks, like sending a notification, updating another document, or performing calculations.
  2. Use Firestore and admin SDK features to enhance the functionality as needed.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.