Send message payload / push notifications from Spring Boot server-side application using FCM (Firebase Cloud Messaging)

FCM with Spring Boot

What is Firebase Cloud Messaging ?

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost. Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload to a client app.

Some Basics Steps You Need To Follow:

  1. Please make sure the client application is registered under Firebase.
  2. Now we need to generate the Firebase SDK admin key. This is basically a JSON file and the purpose of this file is for server side authorization.You can get more details under https://firebase.google.com/docs/cloud-messaging/auth-server.
  3. To get Admin SDK go to Project Setting -> Service Accounts -> Check Java radio button -> Finally click on Generate new private key and save it.
  4. Now we need to use a generated private JSON file in our spring boot application.So for this I am assuming you already have a Spring Boot application.
  5. In my case I have put my private key parallel to the SRC folder in the project structure.

Code Snippets :-

This is the maven dependency we need to add in the pom.xml file.

  • This is the Message POJO.

This is the method which will be called on the initialization of the application. Here In this method we have given the firebase-key.json file which we have generated from the firebase.

This is basically the service method which will be used to send the payload or say push notification. Here the token is basically the FCM token which will be generated by the front-end application and sent along the request. Both front-end and back-end applications need to have the same firebase admin SDK installed. So basically to that particular FCM token ( client application from where it is generated ) the payload / push notification will be sent.

Conclusion

Hence, this way we can send push notification to the client application in real-time. And also we can send message payload in real-time without implementation of web-socket. But there is one limitation of FCM that it will allow a maximum 4kb of payload at a time and you need to have your application either on a platform with SSL certificate or you can have it localhost environment.

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