How to Handle Notifications with FCM

There are various ways of handling Notifications with FCM( Firebase Cloud Messaging). I love how Firebase gives users so many features to test and use even in production-level code.

There are two things to keep in mind :
1. TO save the FCM tokens in the database
2. TO save the notifications in the database

In this example, I will be showing how to handle notifications from a Nodejs Server using Graphql (Apollo-server) backend and MongoDB for the database.

The first and foremost thing to do would be to initialize firebase admin to your server. In the apollo-server, you can initialize context while making your apollo server.

Context is important as it handles all the requests that come into your Graphql API. For making things easy you can also separate them into context.js.

const admin = require('firebase-admin');admin.initializeApp({credential: admin.credential.cert(JSON.parse(Buffer.from(process.env.CONFIG_BASE64, 'base64').toString('ascii')),),});

Now that you have declared admin in context, you can use it everywhere in your resolvers.

To send Notifications through FCM the easiest method would be by using :

admin.messaging().sendToDevice(registrationToken3, message_notification, options).then((response) => {console.log(response.results);}).catch((error) => {console.log(error);});

Where in,

Registration Token : const registrationToken1 = 'dzpCeMDzSe-iCVWWAQjAci:APA91bEQLYqaSOvRLYDUM-4IB3Acu8q99PqaHx2KAr3nqDmx90eC40MESGilfFRckN72lKML2HECV0M7r8sTbSdtPElRjafnUidoaAKxtj-pTmVHPbyPSwc6ImWeh2VKZt6Q';Message :const message_notification = {notification: {title: 'Welcome',body: 'Shreyas',},};const options = {priority: 'high',timeToLive: 60 * 60 * 24,};

would look something like this, wherein you get this token from the frontend. Make sure you save this token in your database so that you can use it later to send notifications to users by using this fcm token. You can save fcm notifications in these three instances :

  1. When a user signs up
  2. When he logs in into the app ( Get the token from the frontend, match it with your user’s fcm token. If same, do nothing, else change the token and delete the previous one)
  3. When users logs out ( delete the token as it is no longer required)

Make sure you maintain FCM tokens properly in the user database.

TO check if the user has deleted the app :

var response = admin.messaging().sendToDevice(tokens, payload);
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
// Cleanup the tokens who are not registered anymore.
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
tokensSnapshot.ref.child(tokens[index]).remove();
}
}
});

In this way, you can check if the user has deleted or not, and with respect to this, you can delete the fcm token in your database as well.

Now, remember to create a schema for notifications so that you can save every notification you send into the database. In this way, your notifications can be completely handled.

--

--

--

Engineer by Profession, Entrepreneur by Choice. Welcome to the world of tech, travel, and poems.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Golang — Date Format in golang

READ/DOWNLOAD=! Functional Programming in JavaScri

Vue js 3 with Webpack 5 — Project setup steps

Banner

Testing with React (3/5 — Good Testing Principles)

Install Node JS di linux atau Ubuntu

Poll UI Design using HTML CSS & JavaScript

Poll UI Design using HTML CSS & JavaScript

Reversed Strings with TypeScript

Getting Started With AdonisJS Backend JavaScript Framework

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sarthak Agarwal

Sarthak Agarwal

Engineer by Profession, Entrepreneur by Choice. Welcome to the world of tech, travel, and poems.

More from Medium

How to implement API Authentication with JSON Web Tokens and Passport

How to use Tin to quickly set up Apache APISIX in minutes

FLO’s Technology Stack

How to create JWT for zoom sdk in nodejs