Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase delete relevant row from database if app is uninstalled

I am using Cloud Firestore to keep app tokens to send push notifications. However, when the user uninstalls and reinstalls the app, Firestore receives a different token for the same user. How can I delete the relevant row of the previous token when the user uninstalls the app?

Thanks in advance.

like image 561
nuhkoca Avatar asked Sep 24 '26 02:09

nuhkoca


1 Answers

Usually you'll want to detect when a token becomes invalid, and remove it at that time. E.g. when a token gets cycled (which happens every few weeks while the user has the app installed), you'll want to use that moment to remove the old token from your database and add the new one. Doing so minimizes the number of outdated tokens you have in your database.

So in steps that means in onTokenRefresh():

  1. Check if there is a token in local storage (e.g. shared preferences). If so, remove that token from both the database and local storage.

  2. Store the new token in both the database and local storage.

But in your case that is not possible, since onTokenRefresh won't be called when the app is uninstalled, and you won't have knowledge of the previous token when it gets reinstalled.

The easiest way to deal with outdated tokens left behind in this and other ways is to delete them when sending to that token fails. The sample of sending FCM notifications using Cloud Functions has a good example of that:

admin
  .messaging()
  .sendToDevice(tokens, payload)
  .then((response) => {
    // For each message check if there was an error.
    const tokensToRemove = [];
    response.results.forEach((result, index) => {
      const error = result.error;
      if (error) {
        console.error('Failure sending notification to', tokens[index], error);
        // Cleanup the tokens who are not registered anymore.
        if (error.code === 'messaging/invalid-registration-token' ||
            error.code === 'messaging/registration-token-not-registered') {
          tokensSnapshot.ref.child(tokens[index]).remove();
        }
      }
    });
  });
like image 83
Frank van Puffelen Avatar answered Sep 25 '26 15:09

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!