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…
Section overview
5 resourcesExplores 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.
- Creating the Function - In your
index.jsfile, 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.
- 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:newDataAddedcommand 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
- Create a function that logs a message when a record is deleted from the database.
- Create a function that modifies a record in the database when it is updated.
- 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article