Implement push notifications with Firebase Messaging and Node.js

In this article, I would be documenting step by step how I was able to implement push notifications with a chat application using firebase cloud messaging and node in no time.

The application already had the chat messaging feature working as expected and I had to add more options such as push notifications and mute notifications, we would cover push notifications in this tutorial.

Therefore, in this article, I would cover the following

  • Prerequisites for this application to work as expected
  • Steps to follow to implement the notifications
  • Conclusion

PREREQUISITES

To implement this feature you need to be running on a stable version of node and you should have an account with google and should have your google payload already configured with the application.

STEPS TO FOLLOW

First, let’s ensure that our server-side application has been properly set up with node and express.

Secondly, download the firebase-admin package if you do not already have it.

npm install --save firebase-admin

This package enables access to Firebase services from privileged environments (such as servers or cloud) in Node.js.

After downloading the package, we need to understand the various ways that notifications can be sent using firebase cloud messaging

Using a topic Condition FCM registration token Device group name (legacy protocols and Firebase Admin SDK for Node.js only) And in this tutorial, we will be using the FCM registration token to identify the device(s) to send notification requests to.

According to the FCM docs,

The FCM registration token is a unique token string that identifies each client app instance. The registration token is required for a single device and device group messaging. Note that registration tokens must be kept secret.

This token is a unique identifier that is auto-generated to a device and it changes per time, so in the application, we ensured that the FCM would change on the login of a device, that means we had to persist this data somewhere to check and verify, hence a Postgres database was used- Do not that this is just a personal choice, you could as well use any other database of your choice or even any of firebase cloud store.

This token would be generated from the client side i.e the mobile device or the web and would be sent to the server on every login request by the client, on the backend I ensured to save the unique token against the device user id on every request hence, using the Postgres UPSERT to keep track of and updating this token.

Lastly, after setting up all necessary package and tools to ensure that the notification works as expected, use this code to send notifications to a particular device

const registrationToken = 'USER_DEVICE_REGISTRATION_TOKEN';

const message = {
notification: {
    title: “John Doe sent you a message”,
    body: “Content of the message”
  },
data: {
    type: 'PERSONAL CHAT',
    click_action: 'FLUTTER_NOTIFICATION_CLICK'
},
  token: registrationToken
};

// Send a message to the device corresponding to the provided
// registration token.

admin.messaging().send(message)
  .then((response) => {
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

This can also be implemented when sending a message to a group and using the admin.messaging().sendMulticast() method.

Here, since we are not just sending a notification message to one user but a group of users, the registrationToken would be an array of the token. This can be done by fetching the tokens of all users belonging to the group from the database and storing them as an array in the registrationTokens variable.

const registrationTokens = ['This would contain a list of all tokens in the group'];

const message = {
notification: {
    title: “John Doe sent a message to the group”,
    body: “Content of the message”
  },
data: {
    type: 'GROUP CHAT',
    click_action: 'FLUTTER_NOTIFICATION_CLICK'
},
  token: registrationTokens
};

// Send a message to all devices corresponding to the provided
// registration tokens.

admin.messaging().sendMulticast(message)
  .then((response) => {
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

In conclusion, these are the steps I followed when implementing the notification feature on the chat app and it works currently with both the mobile and the web clients integrating the application, I hope it helps you while you try to implement push notifications too.

Happy coding.