Firebase / Firebase Cloud Functions

Using Cloud Functions to Trigger Database Events

This tutorial will guide you through the process of using Firebase Cloud Functions to trigger events in your Firebase database. You'll learn how to write functions that react to c…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores building serverless backend logic with Firebase Cloud Functions.

1. Introduction

In this tutorial, we are going to delve into the world of Firebase Cloud Functions and how they can be used to trigger events in a Firebase database. Firebase Cloud Functions are a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests.

You will learn how to write and deploy Cloud Functions that react to changes in your Firebase Realtime Database in real time.

Prerequisites:

To get the most out of this tutorial, you should have some familiarity with JavaScript (ES6), Node.js, and the basics of Firebase.

2. Step-by-Step Guide

First, we'll need to initialize Firebase Cloud Functions in your Firebase project. Open your terminal, navigate to your project's root directory and run firebase init functions.

Once initialized, we'll create a function that gets triggered whenever a new record gets added to the database.

  1. Creating the Function - In your index.js file, you can write a function that gets triggered on database changes:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.newDataAdded = functions.database.ref('/path-to-data/{id}')
    .onCreate((snapshot, context) => {
      // Do something with the new data
    });

In this example, newDataAdded is the name of our Cloud Function, and it's watching the /path-to-data/{id} location in our database. {id} is a wildcard that will match any ID under /path-to-data/. Whenever new data is created at this location, our function will be triggered.

  1. Deploying the Function - Now that we've written our function, we need to deploy it to Firebase. We can do this by running the firebase deploy --only functions:newDataAdded command in our terminal.

3. Code Examples

Let's add some functionality to our newDataAdded function:

exports.newDataAdded = functions.database.ref('/messages/{id}')
    .onCreate((snapshot, context) => {
      const original = snapshot.val();
      console.log('Adding', context.params.id, original);
      return null;
    });

Here, our function is watching the /messages/{id} path in our database. When a new message is added, it logs a message to the Firebase console with the ID of the new message and its content.

4. Summary

In this tutorial, we've covered how to initialize Firebase Cloud Functions, how to write a function that gets triggered by database events, and how to deploy that function to Firebase.

For further learning, you could explore modifying data in response to a change, deleting data, or even triggering a Cloud Function in response to a user event.

5. Practice Exercises

  1. Create a function that logs a message when a record is deleted from the database.
  2. Create a function that modifies a record in the database when it is updated.
  3. Create a function that sends an email when a new user signs up (Hint: you'll need to use Firebase Authentication triggers).

Solutions

exports.dataDeleted = functions.database.ref('/messages/{id}')
    .onDelete((snapshot, context) => {
      console.log('Deleted record', context.params.id);
      return null;
    });
exports.dataUpdated = functions.database.ref('/messages/{id}')
    .onUpdate((change, context) => {
      const after = change.after.val();
      console.log('Updated record', context.params.id, 'to', after);
      return null;
    });
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');

const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword,
  },
});

exports.newUserSignUp = functions.auth.user().onCreate((user) => {
  const email = user.email; 
  const displayName = user.displayName; 

  const mailOptions = {
    from: `${APP_NAME} <noreply@firebase.com>`,
    to: email,
  };

  // The user subscribed to the newsletter.
  mailOptions.subject = `Welcome to ${APP_NAME}!`;
  mailOptions.text = `Hello ${displayName || ''}! Welcome to ${APP_NAME}. We hope you will enjoy our service.`;
  return mailTransport.sendMail(mailOptions)
    .then(() => {
      return console.log('New welcome email sent to:', email);
    });
});

In the last exercise, the function uses the nodemailer package to send an email. You need to replace APP_NAME with your application name and set up the gmail.email and gmail.password in Firebase Functions config.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help