Search code examples
firebasefirebase-cloud-messagingfirebase-notifications

How to send notification based on role?


How to send notification based on role. For example if I have 5 different roles I select only one role then that role people should get notifications using FCM and remaining role should not get for this. Do we need to write service in back-end(using SPRING,PHP)?


Solution

  • The easiest way to accomplish this is to subscribe each client to a topic based on their role. For example in the Android app:

    FirebaseMessaging.getInstance().subscribeToTopic("myRole");
    

    Then you can send a message to all users in a role with the Firebase Admin SDK with:

    admin.messaging().sendToTopic("myRole", { 
        "notification" : {
          "body" : "great match!",
          "title" : "Portugal vs. Denmark"
        }
    })
    

    A few things to note:

    • Sending a message to devices requires that you specify the FCM Server Key. As its name implies, this key should only be used on a server or another environment that you control. The Admin SDK runs with full credentials, so automatically has access to the FCM server key.
    • Anyone can subscribe to any topic. So in the above example, malicious coders could also subscribe themselves to topics of roles they are not part of. If this is a concern for your app, you should not use topics but instead maintain your own server-side mapping of FCM registration tokens to roles. This example from the Cloud Functions documentation is a good place to get started with such a custom mapping