Cloud Functions for Firebase. In a nutshell, they are small pieces of stand-alone JavaScript functions which are deployed to Firebase servers and executed in response to various events — such as a change in Firebase Database or a new user login, without the need to manage a server.
Bootstrap your server side development —Cloud Functions for Firebase manages the infrastructure for you, so the only thing left is to write your business logic without any reference to the environment (scale, users, etc…).
> firebase deploy --only functions
> firebase deploy --only functions:welcomeEmail
How to start sending email using Firebase Cloud Function ?
1. Installing Firebase CLI via npm
> npm install -g firebase-tools
2. Initialize the firebase project
> firebase init functions
myproject
+- .firebaserc # Hidden file that helps you quickly switch between
| # projects with `firebase use`
|
+- firebase.json # Describes properties for your project
|
+- functions/ # Directory containing all your functions code
|
+- package.json # npm package file describing your Cloud Functions code
|
+- index.js # main source file for your Cloud Functions code
|
+- node_modules/ # directory where your dependencies (declared in
# package.json) are installed
Send Welcome Email On User Creation
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const mailTransport = nodemailer.createTransport(
`smtps://test.user@gmail.com:test@123@smtp.gmail.com`);
exports.sendWelcomeEmail = functions.auth.user().onCreate(event => {
const user = event.data;
const email = user.email;
const displayName = user.displayName;
const APP_NAME = 'Demo App';
const mailOptions = {
from: `${APP_NAME}`,
to: email
};
mailOptions.subject = `Welcome to Demo App!`;
mailOptions.text = `Hey ${displayName || ''}! Welcome to ${APP_NAME}. I hope you will enjoy our service.`;
return mailTransport.sendMail(mailOptions).then(() => {
console.log('New welcome email sent to:', email);
});
});
Send Good Bye Email On User Deletion
exports.sendByeEmail = functions.auth.user().onDelete(event => {
const user = event.data;
const email = user.email;
const displayName = user.displayName;
const mailOptions = {
from: `${APP_NAME}`,
to: email
};
mailOptions.subject = `Bye!`;
mailOptions.text = `Hey ${displayName || ''}!, We confirm that we have
deleted your ${APP_NAME} account.`;
return mailTransport.sendMail(mailOptions).then(() => {
console.log('Account deletion confirmation email sent to:', email);
});
});
3. Deploy firebase functions
> firebase deploy --only functions
Resources
Questions ?