Use Firebase Cloud Function to Send Notifications to App Users (Tutorial)

A server is costly to maintain, and Google knows this better than your cheque book.

Firebase Cloud Function to Send Notifications

For the same reason, Google offers Firebase Cloud functions with 125K invocations, 40K GB-seconds, and 40K CPU-seconds at no additional cost.

Isn't it fantastic?

Firebase changed the game in the development world by offering over a dozen important features.

Cloud Function is one of the capabilities that allows you to build and publish code that reacts to events from Google Cloud services.

What's the best part?

All of your code is hosted on Google servers, which are responsible for all of your computing processing power.

Aside from that, it protects your app from being hacked and other harmful measures used to harm it.

Steps to Notify App Users Using Firebase Cloud

So, let's get started with your first cloud function deployment.

We'll develop a TypeScript function that runs in the Node.js environment.

TypeScript is similar to JavaScript, but it is superior.

Step 1 – Install Node

If you haven't already done so, go to nodejs.org and download the software.

Are you perplexed? Don't be concerned.

You may also check your system's node version by typing "node -v" at the cmd prompt and "npm -v" for npm, as seen in the screenshot below.

Node should be at least version 6 and npm should be at least version 5.

The Firebase CLI must be installed after Node.js has been installed.

How do you do it?

You may use NPM to instal the Firebase CLI by copying the following command:

npm install -g firebase-tools

and paste within the cmd prompt and hit Enter.

After putting in, you'll conjointly check it’s a version with “firebase –version” cmd

Step 2 – Create a New Project in Android Studio

  1. Now open android Studio and make a brand new project.
  2. Following that, From the top bar, select Tools -> Firebase. A new window will open on the right side.
  3. Simply scroll down and select FireStore -> Read and write a document using Cloud Firestore from the drop-down menu.
  4. After that, select Connect to Firebase from the drop-down menu.
  5. You can either Create a New Project or Select an Existing Project in the dialogue box that displays. Isn't it true that I said to use an existing project?
  6. Then select Connect to Firebase.
  7. Now you must add dependencies to your app, so select Add Cloud Firestore to Your App. Now a popup box displays, and you must click Accept Changes to proceed.

Step 3 – Initialize Firebase

  1. Create a new folder in which you'll save your function files.
  2. After that, open the folder and type "cmd" into the search field. It will open a cmd prompt with the path to the folder.
  3. Now copy the cmd below and paste it into the cmd prompt, then press Enter. firebase init
  4. To continue, press Y and then Enter.
  5. As you are working with a function, simply drag the arrow key down and select Function, then press the space bar until a small (*) appears and press Enter.
  6. Then choose "Use an Existing Project" from the drop-down menu.
  7. After that, choose your project.
  8. Choose "TypeScript" as a function.
  9. Enter by pressing "Y."

Step 4 – Write Function

Some files have now been uploaded to your app folder, as you can see.

Then drag your Function folder into Visual Studio Editor.

Now, in the index.ts file, type the following method.

import * as functions from 'firebase-functions';                
//To construct Cloud Functions and set up triggers, use the Cloud Functions for Firebase SDK.
import * as admin from 'firebase-admin';                        
//To access the Firebase Firestore Database, use the Firebase Admin SDK.

admin.initializeApp(functions.config().firebase);               
//This will start the Firebase application. 
//The notification is the collection id in this case.
//The notification id is the unique identifier for each notification.
exports.sendNotification = functions.firestore.document('notification/{notification_id}').onWrite(event=>{

    const title=event.after.get('title')                            
//get the title back
    const body=event.after.get('body')                              
//reclaim the body

    //generate a payload for notification information
    const payload={                                 
//We create payload as a const here.
        notification:{
            title:title,                           
//add a title to the payload
            body:body                               
//body in the payload title
        }
    }

    //make a topic
    const topics = "notification"

    //Use FCM to deliver a notification using a topic.
    //.sendToTopic(topics, payload) need 2 parameters 
    //The first is subject: we utilised topic as a constant here, but in the real programme, we primarily utilise topic as a variable.
    //Model of subscription/following. Only those that follow will be notified.
    //The second is the payload, which is similar to sending an extra message detail.
    return admin.messaging().sendToTopic(topics,payload).then(res=>{              
    console.log('notification sent ')                   
//"Notification sent is displayed within the log files" if notification is delivered.
    }).catch(err=>{                                     
//Here's where you'll catch a mistake.
    console.log('notification sent '+err)            
//If the notification fails, the error "notification err" appears in the log files.
    })
})

Furthermore, the Cloud Function runtime requires JavaScript code to function.

However, because I'm using TypeScript, it must first be compiled into JavaScript before being deployed.

You don't have to worry about it because Firebase CLI will take care of it for you when you run the deploy cmd.

Furthermore, it will create the JavaScript files in the lib subdirectory automatically.

Step 5 – Create a Firestore Database

  1. Go to console.firebase.google.com and open your project.
  2. Then, on the left side, select Database.
  3. Now select Create Database from the drop-down menu.
  4. Because we're making this programmed for educational purposes, a popup box comes with the option to "Start in test mode." However, if you wish to use this function in your app, you can choose production mode.
  5. Then press the Next button.
  6. Now click Done after selecting cloud Firestore Location.
  7. Now press the Start Collection button.
  8. In the popup box that displays, type in the Collection Id and then click Next.
  9. To generate an automatic id, click on Auto-ID.
  10. After that, you may add a title and a body to your document and save it.
Now your Firestore looks like this.

Step 6 – Deploy the function

  • Everything is working perfectly now. It's time to put the function into action.
  • Then you must go to the command prompt. Copy the cmd below and paste it into the cmd prompt, then press Enter. firebase deploy
  • After that, go to Console -> Function -> Dashboard to see if a function was successfully added.

Step 7 – Create a Firebase Cloud Messaging account (FCM)

  1. Return to the Android studio to set up FCM.
  2. Then go to Firebase Assistant -> Cloud Messaging -> Firebase Cloud Messaging Setup.
  3. Then, select Add FCM to Your App.
  4. When you click Accept Changes in the dialogue window, it will add a dependency to the build gradle (app) file.

Step 8 – Run the App

Everything has been completed successfully. Simply run the app and examine the results as shown in the image below. When the app is in the foreground, background, or is killed, a notification will be sent.

A notification is generated whenever a new record is added to the database. You can utilize some code in your project to dynamically add data from users.

Post a Comment

Previous Post Next Post