Firebase Push Notifications For A Specific Browser

I have a web page which shows real-time notifications like facebook does. I want to send notifications to a specific user but how could I make my back-end that sends these notifications to know the token of each user? Is there any way to make firebase maps between a user id known to my back-end and the token it uses to send the actual notification? I am thinking of using the messaging.onTokenRefresh() to send ajax request to the backend to keep track with the current token. and whenever the back-end send a notification it will grape it by something known like a user id. But I wander if there is something better than that?!



Keeping a mapping between users and their FCM tokens is a common approach. It's sometimes referred to as a token registry.

A few things to keep in mind:

  • A single user can have multiple tokens, such as when they open your app on multiple devices.
  • Tokens can expire, in which case you'll want to prune them from the registry. A simple way to do this is when you get an error while trying to send to a token as shown in this example.

A simple alternative is to create a topic for each user (for example with their UID), and send to that. Some things to keep in mind there though:

  • Topics are public, so anyone who knows the topic ID can subscribe to it.
  • You won't need to maintain your own device registry in this case, as FCM topics do this for you behind the scenes.