0
votes

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?!

1
Yes, you can certainly pair up users and their devices' tokens. This is very common.Doug Stevenson
@DougStevenson Could you please tell me how? I am talking about a web page not a mobile appEng.Helewa
Based on what you wrote, it sounds like you are on the right track. If you're looking for full instructions on how to manage your backend that actually works with the tokens, that's out of scope for a Stack Overflow question. If you have a specific problem with programming, that's what this site is for.Doug Stevenson

1 Answers

1
votes

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.