Featured Image
Software Development

Cloud Function for Firebase

Getting Started with Firebase Functions

Firebase function will let you run your code on any event occurrence of firebase or on any request call. It will let you deploy your code on its server environment. For some basic information, you can view this video.

Below are the steps to start with a simple firebase function (sends push-notification to provided user’s FCM token)which will be triggered on event-triggered on cloud Firestore database. Its servers will listen for events and run the function when the event is triggered.

Setting up Firebase CLI and Project

1. First, to run functions you need to install Node and npm.

2. Once you have installed it you need to install firebase-CLI, from where your firebase functions will be managed.

$npm install -g firebase-tools

It will install firebase commands globally.

3. Sign into your firebase using your google account.

It will connect your local machine to Firebase and grants you access to your Firebase projects. You should have one firebase project in which you can deploy your function.

$firebase login

It will prompt for permission to gather anonymous usage data before displaying a browser window in which you need to select the Google account associated with your Firebase development project. Select an account and agree to the terms and conditions, after which you will be successfully logged in.

Writing and Deploying the Firebase Function

4. Create a function

$firebase init functions

It will prompt you for the selection of the firebase project, select any one for which you need to create function. And then you will be prompted to select a language for writing function, here we are going to select “Javascript”. Also, install all its npm dependencies. Below is the screenshot:

Firebase project and language selection prompt screenshot

Now your project has been created.

5. Edit the file index.js to write your code and add below lines.

Below code is used to send push notification for a user with his/her fcm_token.

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendPushNotification = functions.firestore.document(`/YOUR_COLLECTION_NAME/DOCUMENT_ID`).onUpdate((change, context) => {
var token = "YOUR_FCM_TOKEN"
    
    //payload for push notification
    var payload = {
        "notification" : {
            "body" : "MESSAGE_BODY",
            "title": "MESSAGE_TITLE"
        }
    }
    
    admin.messaging().sendToDevice(token, payload).then((res) =>{
     console.log('Push Success:', res);
     return 0;
    })
    .catch((error) =>{
        console.log('Push Error :', error)
    });
});

Make sure that specified collection_name and its document_id must be present in your cloud firestore database.

And this function will be triggered on any updates of the document.

6. Deploy and execute the function

$firebase deploy --only functions

After you run this command, the Firebase CLI outputs the URL for any HTTP function endpoints. And now you are ready to roll.

You can view your function logs in Firebase Console -> Develop -> functions ->Logs. See below screenshot:

Screenshot of viewing function logs in Firebase Console

That’s it, this is how I created my first firebase function.

Also read: Streamlining Android Testing: Harnessing Jenkins and Firebase Automation

author
Kirtan Khatana
I work as a Back-end Developer in Aubergine Solutions. I am a certified AWS Developer Associate having a broad knowledge of AWS services.