Skip to content
Advertisement

How to get Firebase token of current user

I’m buildning an app where a logged in user can invite another user through pressing a button, so then the invited user will get a push notification. My idea is that if I can save the token for each user in the database, then when a user presses the “invite button” it will find that users token in the database and after that I will somehow use it to send a notification to that user. I don’t know if there is a better way of doing it, but I didn’t find anything else on it so that is my current plan.

Now I have run into some issues regarding how to save the token to the database. I want to do save it to the database whenever a user creates an account or the token changes.

JavaScript
JavaScript

What I want to do is to save the token in the user in the database together with the other variables such as username, age, etc.

I was hoping there would be something like this to get the token, but it doesn’t seem that way:

JavaScript

So what I’m really asking is how do I get the current token for the user?

Advertisement

Answer

Firebase Cloud Messaging tokens are unique to the device, not the user. It doesn’t know anything about Firebase Auth users, and Firebase Auth doesn’t know anything about FCM device tokens.

You will need to store a mapping of users to their device tokens. Since a user could be using multiple devices, your data structure should allow for multiple tokens for each user. Then, your backend code should query for those tokens and send the message to each one of them (if that’s what your users want).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement