0

I am able to send the notification to a single user by getting its fcm token.

Consider this simple case of something like Instagram: A user(X) sends a friend request to some different user(Y)

Now I want to send a notification to user Y, how should I do that?

The only way I can think of is to store the fcm token into the user data base and send on basis of that, Is there a better method?

  • You can use `npm` module https://www.npmjs.com/package/@firebase/messaging Follow article https://firebase.google.com/docs/cloud-messaging/send-message – Sandip Nirmal Sep 12 '21 at 14:14

1 Answers1

2

Firebase Cloud Messaging has three ways to target messages:

  1. You send a message to a FCM token/device ID.

    An FCM token identifies a specific app on a specific device, so you're targeting a single app instance.

  2. You send a message to a topic.

    An app instance can subscribe to any topic, so you're targeting everyone who has subscribed to the topic here.

  3. You send a message to a device group.

    You can group FCM tokens into groups of up to 20, which you can then target with a single message.

Of these options, the first and third are by far the most common.

You'll note that there's no options to send a message to a user, as FCM doesn't have the concept of a user. A user can be signed in to the same app on multiple devices, in which case they'd have multiple FCM tokens. And (less common, but still common enough to think about) multiple users can sign into the same app on the same device.

You'll want to set up a database somewhere (sometimes referred to as a token registry) where you map the FCM tokens to how you want to send messages. So in your case, storing the tokens for each user makes sense, and is in fact quite idiomatic.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks for the help. I think that solves some of my problem there – Sarthak Agarwal Sep 12 '21 at 15:36
  • How to prevent sending a notification to an user who was logged in a device but he/she signed out? Would updading/inserting tokens on login/signup and removing tokens from registry on singout or when token goes invalid be sufficient for all the use cases? – Bugzilla Sep 12 '21 at 16:35
  • There's nothing built in. As FCM doesn't know anything about users, you will have to delete the token when the user signs out. Search is your friend here: https://www.google.com/search?q=%5Bfirebase-cloud-messaging%5D+clear+token+on+logout – Frank van Puffelen Sep 12 '21 at 16:39
  • And I have to store the fcm token in my server right? – Sarthak Agarwal Sep 14 '21 at 05:51