Firebase Cloud Functions Part 1
If you are using serverless to build your backend probably you heard about Firebase cloud functions. firebase provide us to a very easy way to build and deploy our backend using Nodejs using javascript or typescript. In this article, I’m going to show you what are the different function types we can use in firebase to build our backends easily.
Pre-Requirements
firebase account, Nodejs Installed on your computer, Firebase tools install as global using node js
Types fo Firebase Cloud Functions
Normal Functions (REST Apis)
Authentication Triggers (Trigger when new user signup using firebase authentication)
Storage Triggers (Trigger when storage updates)
Firestore Triggers (Trigger when firestore updates)
Realtime Database Triggers (Trigger when realtime database updates)
Pubsub (Background Functions)
Create a Firebase Project
Create a Firebase Project using firebase console by navigating https://console.firebase.google.com/ and update your project to Pay as you go
Create Function Project
Create a Firebase function project using firebase CLI
Open terminal and type npm i -g firebase-tools
Then in the project folder open terminal again and type firebase init functions
You’ll see this options list select User an existing project and select the project that you create using firebase console.
Then you’ll see this to select the language Javascript or Typescript, in this case, I’m using Typescript. And in next they ask to Do you want to use ESLint to catch probable bugs and enforce style? Y and enter
Do you want to install dependencies with npm now? to this, I’m using N because I’m going to use Yarn, not npm. If you don’t install yarn to your computer you should type Y and enter.
Not Our project is created successfully.
Normal Cloud Function Implementation
Now open your project folder using a text editor in this case I’m using VsCode. (Open your text editor inside functions folder)
inside functions folder, we can see index.ts file (If you use javascript you’ll see index.js file)
Inside the index file, there is simple boilerplate code, we are going to deploy this code and see how this works.
import * as functions from "firebase-functions";export const helloWorld = functions.https.onRequest((_request, response) => {functions.logger.info("Hello logs!", { structuredData: true });response.status(200).json("Hello from Firebase!");});
In here helloWorld is the function name and after we deploy our function we can access these functions using URL/helloWorld.
To deploy this function open your terminal inside functions folder and type
npm run deploy or yarn run deploy
Once all done you’ll see this message with your endpoint url
copy that function URL and open postmen and send a get request, you’ll see some message like bellow,
If you see this message congratulation you are successfully deploying your firebase cloud function. this is a simple response but you can be using services inside this function like you do in severs. this is the normal REST function using firebase cloud functions.
Authentication Triggers
Another type of firebase cloud function, we can trigger a function when new user signup using firebase authentication. these functions run as a background function, using this function we can add a newly created user to our database or otherthings like send and welcome email etc.
To test these functions first we need to go to the firebase console and enable firebase authentication via email and password.
Once this was done we can do the implementation part.
import * as functions from "firebase-functions";import * as admin from "firebase-admin";import { UserRecord } from "firebase-functions/lib/providers/auth";admin.initializeApp(functions.config().firebase);
export const userCreate = functions.auth.user().onCreate(async (user: UserRecord) => {functions.logger.info({message: "Newly Created User Details",user},{ structuredData: true });});export const userDelete = functions.auth.user().onDelete(async (user: UserRecord) => {functions.logger.info({message: "Newly Created User Details",user,},{ structuredData: true });});
In here I have created two cloud function one is trigger when a user was added and another one is trigger when a user was deleted. I have added firebase logs then we can see if these functions trigger correctly.
once again we need ti to deploy our functions using
npm run deploy or yarn run deploy
once all done go to the firebase console and authentication section add new user.
Once new user added go to the functions logs section and filter userCreate function and you can see the message like this,
this means our authentication trigger function is successful.
Now we test userDelete Trigger function to do that we need to go to the authentication section and delete one user and see logs in deleteUserLogs.
If you see logs like this your deleteUser function is successful.
Now we Build the Normal cloud function and Authentication triggers.
Here is the full code.
import * as functions from "firebase-functions";import * as admin from "firebase-admin";import { UserRecord } from "firebase-functions/lib/providers/auth";admin.initializeApp(functions.config().firebase);export const userCreate = functions.auth.user().onCreate(async (user: UserRecord) => {
functions.logger.info({
message: "Newly Created User Details",
user},{ structuredData: true })
});export const userDelete = functions.auth.user().onDelete(async (user: UserRecord) => {functions.logger.info({message: "Newly Created User Details",user},
{ structuredData: true });});export const helloWorld = functions.https.onRequest((_request, response) => {functions.logger.info("Hello logs!", { structuredData: true });response.status(200).json("Hello from Firebase!")
});
In the next part, I’m going to implement Storage triggers, Realtime database triggers and Pubsub (Background Functions)
Thank you.