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.
To get the most out of this tutorial, you should have some familiarity with JavaScript (ES6), Node.js, and the basics of Firebase.
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.
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.
firebase deploy --only functions:newDataAdded
command in our terminal.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.
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.
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.