Adding registration tokens in an empty device group throws bad request in Firebase - firebase

We have one device group per user for our mobile app. When a new user sign up, a new device group with registration token is created via create operation from app server and its notification key is stored with user data.
When a user sign out of the app, its registration token is removed from the notification key via remove operation as we don't want to send personal notification for that user to that device anymore. This step returns same notification key.
When a user sign in again, we try to add the registration token via add operation using the stored notification key. This action returns 400 (Bad Request) status from Firebase server.
Is this expected behavior? If so, how to handle the above use-case?

Notification key for a device group is removed as soon as the token count reaches zero.
I ended up using topics instead of device groups for this use case.

Related

What does firebase use to generate a registration token?

I have already created a push notification system using firebase. It generates and saves a token for a user, then upon login displays their subscription status. It works fine, unfortunately it’s only one device per user, the most recent device they logged in on. I’d like to allow for multiple devices per user.
I’m assuming firebase uses some ID unique to each device to generate a token. If I’m wrong in that assumption, please point me in the right direction.
As Doug commented, since FCM doesn't associate its tokens with users, this is probably some limitation in your implementation.
You'll want to allow multiple ID tokens per user in your database, and then send to all tokens for the current user. If the device/app install can be shared between users, you'll want to remove the association between the user and the token for that installation when the user signs out/a new user signs in.
On associating tokens with users, see:
Is FCM (firebase cloud messaging) Token for one device or for one account?
When to register an FCM token for a user
How to get Firebase user id from FCM token? (in admin code on server)
And then finally you'll also want to clean up any tokens that FCM flags as not valid anymore, as otherwise you'll keep adding more and more tokens, which may not be valid anymore.
On deleting expired tokens, see:
When device token expires, is it automatically removed from FCM device group?
How do I identify and delete the expired FCM token on server?

FCM Token - When should I store/save it on my DB?

I am not sure what a proper FCM token handling mechanism would be so I’m writing our process down here just to get some validation or suggestions for improvements:
Fetch FCM token on client Login (Flutter)
Save FCM token on our Database (Using our REST API)
Delete FCM token on Logout (Using our REST API)
Q1: Should we be getting the FCM token more often than just on login? AFAIK, FCM token only changes on app re-installs, clearing cache, etc. Does this also include app-updates from the PlayStore? In that case, should we save the FCM token on every app launch since the user will remain logged in after an app update and hence we wouldn't trigger the save FCM call.
Q2: Did I mention the right way to handle deleting FCM tokens from our DB? We don’t want the user to keep getting notifications once they have logged out.
Q3: An add-on idea is to send the device_id to the server along with the fcm_token so that server deletes all previously saved FCM tokens for that device_id. This is useful to not have useless tokens on the DB from cases where the user uninstalls the app without logging out (which means that the DELETE fcm_token call never went through.)
The FCM token is refreshed under conditions that you don't control, and those conditions have even changed over time. To handle token updates properly, you'll need to implement both initially getting the token and then monitoring for token updates.
Note that FCM tokens are not associated with a user. It is fine if you want to associate them with a user, but it's up to your application code in that case to maintain the association. So that for example includes deleting the token from your database when the user signs out, as you're doing in step 3. 👍
For keeping your token registry clean, you can indeed do this proactively as you intend, or reactively as shown here: https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js#L76-L88
Hi Rohan fundamentaly you should use below logic to save tokens on server.
Step1:
as soon as you get token in callback whether new or same try to save it localstorage.
Step2:
Call your REST API to save it to your server. it is upto you if you want to send unique user identifier along with the token.
Step3:
It is obvious you will recieve token callback a lot of time so you can check whether you have similar token in localstorage, it means you have the token on the server so no point calling REST API.
Step 4: Now your app can send events back to server and based on it trigger Push notifications to the users.
Step 5: You can Add/update user token based on uniqye user identifier. In some cases a user can be guest user, so your app should generate guest userId and link it with token.
Stay safe.

How a Firebase token is generated?

I'm doing analysis on Firebase Token and understood below points:-
-> A Firebase token is saved in database which will be used for sending notifications.
-> The token generally do not expire except in the following cases:
- The app deletes Instance ID
- The app is restored on a new device
- The user uninstalls/reinstall the app
- The user clears app data.
-> When we use a token which is expired we get errors like Not Registered from the response while sending messages.
-> To avoid the error, we should be deleting the token from database.
However I have found that If we login to a cloud application (which is my app currently), a new fcm token gets generated when i logged in to a new browser say FireFox, Edge etc.
So, the token is generated based on browser or System IP or what exactly the Fcm uses to generate a token ?
The method used to generate the token is an implementation detail, and you should not depend on that to build your app.
A token uniquely identifies a device. Each device receives messages independently of each other, and does not know anything about the user of that device. It's expected that if a user signed into an app on multiple devices, that each device would generate a unique token. If you want to send message to a user, you will have to map each of the user's device tokens in your own database, and send the message to each of them, or only the ones that the user chooses.
You can expect that device tokens might change over time. If you send a message to a device, and the API tells you that the token is not valid, you should simply delete it from your records.

Push notifications by username

I have been looking for ways to send notifications to specific users and what I found was that I need the device token to do that.
I have tried Firebase and Ionic Cloud Service to do some pushs and it worked fine, but I'm wondering if it's possible to register a service with a key -> value, for exemple, register with the username and the token. If so, how can I do it?
And what is the best service to do it?
Thank you in advance for the help.
P.S.: I'm not asking for code, just the theory.
From you question [for example, register with the username and the token. If so, how can I do it?] I understand following.
You mean to say, there is a mobile app, which user will sign up to use and you want to send the notification to registered user i.e. get send push notification by username.
To solve this, you can follow the steps mentioned below.
On app launch when you get FCM registration token, save it to some intermediate location such as local storages along with device-id, mobile details etc..
Create a backend API which can save username and registration token in DB.
When a user signs up or signs in, then fetch the registration token from local storages, post username, token to backend API to save it. You can make backend API bit intelligent to handle multiple devices of the single user, distinguishable by device-id, mobile details.
Then while sending API from the backend, you can fetch all registration ids of a single user and send the notification to that users using all tokens of that user in FCM API. Use registration ids as JSON array in "registration_id" field. FCM Document - link.

How can I know that a Firebase Cloud Messaging token is out of use?

A single user can have multiple devices connected to his account.
Because of that he can have multiple cloud messaging tokens.
Everytime the user opens the app the token from that device is send to the app server and saved there.
What happens if a user uninstalls the app from one of his devices? I have no chance to tell the server that the token is not longer in use.
Can it occure that I notify an other user instead since this other user has acquired the not longer used token from the original user?
What happens if a user uninstalls the app from one of his devices?
Usually, when your app is uninstalled, it is advisable for you (the developer) to automatically make sure that the corresponding registration token is deleted from your own App Server.
Can it occure that I notify an other user instead since this other user has acquired the not longer used token from the original user?
No. Each registration token is unique per each app instance. So rest assured that if a registration token is invalidated/expires for whatever reason, no other user will be able to use it. Sending a message to an invalid/expired registration token will result to a NotRegistered error.
Tokens are not re-used so there should be no risk of notifying another user. Tokens cannot be acquired by one user from another.

Resources