11

I'm considering a scenario where a user installs the app on multiple devices say mobile and desktop; and generates two different tokens.

My current plan is to store both the tokens for the user in database. However, I'm not sure how do I handle the scenario when the token is expired and a new token is generated?

For example, this could be the simple db structure -

id | user_id | token
-------------------------
1  | 1 | asdlgkj090sdf8q (desktop)
2  | 1 | zlkroqiuoiquoio (mobile)
3  | 2 | mnnjnjnjnjojuhq
4  | 2 | 498slkdsflksjfl

If the token for mobile gets updated; I've no way of knowing which row to update.

How do I handle such scenario?

TheBigK
  • 451
  • 5
  • 17

2 Answers2

9

If you want to remove the old token after a new one was generated, I can think of two ways of doing this:

Option 1: Introduce a client id

You could give each client a unique ID that you use to identify it. When you send the new push token to the server, you need to make sure that you also pass the client ID to the server. Your database structure would then look something like that:

id | user_id | client_id | token
------------------------------------------------------ 
1  | 1       | tthdh     | asdlgkj090sdf8q (desktop) 
2  | 1       | di4dq     | zlkroqiuoiquoio (mobile) 
3  | 2       | 5efgd     | mnnjnjnjnjojuhq 
4  | 2       | 56eff     | 498slkdsflksjfl

In your update script (on the server) you will check if a push token exists for the given client id and then either replace the old one or insert a new row.

Option 2: Remember the old token

The second option would be to store the current token on the client, and if it is updated you send both the old and the new token to the server. Then you search for the old token and replace it (or insert a new row if the old token is not present).

If you want to find out if a given token is expired, check this answer. Another approach that I've seen in the Firebase documentation was to remove the token that was used to send a push message if sending the message failed.

Markus Penguin
  • 1,581
  • 12
  • 19
4

The best way to do that is the described method in documentation of server-integration from google:

When a message is sent via an admin SDK, invalid/expired tokens will throw an error allowing you to then remove them from the database.

So when you send message, response will return from API contain result status with possible values if error can be found in table 9 here:

If response status 200 + and error -> NotRegistered >> that is mean token expires, so delete this token from your database.

AnasSafi
  • 5,353
  • 1
  • 35
  • 38