ndduong
ndduong

Reputation: 439

What's the best way to store FCM tokens?

I am trying to send push notifications programmatically to and iOS app using the Cloud Functions. In order to do this, I need to get the target user FCM token.

My idea of doing this is storing a dictionary of user emails and their FCM tokens on the real-time database. This way, whenever the Cloud Functions need to send a push notification to the user, it can look up the current token.

However, while looking at the docs, I noticed Firebase said this:

An ID generated by the FCM SDK for each client app instance. Required for single device and device group messaging. Note that registration tokens must be kept secret.

If FCM tokens need to be kept secret, then how should I send a push notification programmatically from Cloud Functions? Or is storing on the database "secret" enough?

Upvotes: 11

Views: 7414

Answers (2)

Miguel Q
Miguel Q

Reputation: 3618

Storing it in the DB/any database that is server side, should be secured anyway.

The goal is to not making the tokens "public" for everyone to fetch otherwise someone can steal it? And abuse.

In my case, each time a user login in the app I'm able to match their username/a user_id that identifies that user with the received client device token.

For example after obtaining the token and the user is logged, then I send POST to my server with that token for that user. On logout I POST/DELETE to my server that want to inactivate/Delete that token link.

Also the device token might expire and change, so each time the client has a token I add it to the database again. So in the end the backend will have a list of tokens per user_id. And send to every device tokens that match the user you want to notify.

During that backend process if the result of the call to the FCM service returns the error "not registered" then I know for sure that device token invalid/expired, and I can safely remove it from the database. I believe this is a good approach.

Upvotes: 4

AL.
AL.

Reputation: 37768

Storing the token on the Firebase DB should be secured enough (I think the docs needs re-wording on this). Make sure that the node you plan to save the registration tokens is properly secured with the Firebase Rules - allowing only the corresponding users to read them. However since you're using Cloud Functions to read them, you should be fine.

Upvotes: 11

Related Questions