67

When do FCM tokens expire? Is it at 6 months?

shashank chandak
  • 544
  • 5
  • 13

4 Answers4

116

It doesn't expire though. It renews itself if one of the following happens.

According to https://firebase.google.com/docs/cloud-messaging/android/client:

  1. -The app deletes Instance ID
  2. -The app is restored on a new device
  3. -The user uninstalls/reinstall the app
  4. -The user clears app data.

Monitor token generation

The onTokenRefreshcallback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}

EDIT

onTokenRefresh() is now deprecated. onNewToken() should be used instead.

Felipe Mosso
  • 3,907
  • 11
  • 38
  • 61
user2967888
  • 1,309
  • 1
  • 7
  • 9
  • 19
    How can the server know if the new token is for a new device or just sent again to replace an old token? – Günter Zöchbauer Jan 16 '18 at 08:54
  • 1
    Compare with device id or userID if you have those fields in serverside, and update accordingly – Hitesh Dhamshaniya Mar 10 '18 at 04:42
  • 2
    This is very interesting and makes sense considering the token generation strategy, can we get the source, please? – cutiko May 15 '18 at 18:50
  • 1
    @cutiko I think this is the [Link](https://firebase.google.com/docs/cloud-messaging/android/client#sample-register). However I am having difficulties understanding this answer. In the documentation it is written that the token changes in those cases but it doesn't explain what happens with the original token! – Noah Martin Jun 19 '18 at 12:11
  • 1
    @NoahMartin is not valid anymore if you store it in some place and then try to use it as the destination for any new FCM it won't work – cutiko Jun 19 '18 at 16:04
  • Link to this answer's source: https://firebase.google.com/docs/cloud-messaging/android/client#sample-register – Christopher Stephan May 27 '19 at 08:03
2

As stated in the documentation here the token doesn't expire it only changes on certain events. Whenever a new token is generated a method onTokenRefereshId is called.To implement this create a class which extends FirebaseInstanceIdService and override the onRefreshToken as follows:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(refreshedToken);
    }
}

Also do not forget to register this service in the manifests

<service
    android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>
shashank chandak
  • 544
  • 5
  • 13
  • 2
    This intent action is now called `com.google.firebase.MESSAGING_EVENT`, see here - https://stackoverflow.com/questions/51148336/what-to-do-with-the-instance-id-event-action-with-firebase-17-0-1 – Vadim Kotov Dec 06 '19 at 16:22
1

Using firebase admin, you can do this:

async function isValidDeviceToken (deviceToken) {
  const {
    results: [notifResult]
  } = await firebaseAdmin.messaging().sendToDevice(
    deviceToken,
    {
      notification: {
        title: 'Device Registration',
        message: 'Your device has been registered.'
      }
    },
    {
      dryRun: true
    }
  );

  // returns true if valid, false if not.
  return !notifResult.error;
}

what it does is it will check if the provided deviceToken is valid, behid the scene, firebase admin checks if the deviceToken is registered. If it is not registered, it will return the following error:

{
  error: FirebaseMessagingError: The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages.
      at FirebaseMessagingError.FirebaseError [as constructor] (/Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/utils/error.js:44:28)
      at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/utils/error.js:90:28)
      at new FirebaseMessagingError (/Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/utils/error.js:256:16)
      at Function.FirebaseMessagingError.fromServerError (/Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/utils/error.js:289:16)
      at /Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/messaging/messaging.js:105:63
      at Array.forEach (<anonymous>)
      at mapRawResponseToDevicesResponse (/Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/messaging/messaging.js:101:26)
      at /Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/messaging/messaging.js:370:24
      at processTicksAndRejections (node:internal/process/task_queues:94:5)
      at async isValidDeviceToken (/Users/aprilmintacpineda/projects/my-app/test.js:13:7) {
    errorInfo: {
      code: 'messaging/registration-token-not-registered',
      message: 'The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages.'
    },
    codePrefix: 'messaging'
  }
}
aprilmintacpineda
  • 1,114
  • 13
  • 21
0

If the app is not used for more than 1 to 2 months it becomes at status STALE, so the subscription and ability to refresh token stop. Its not a fixed time, but based on firebase documentation it suggest to check invalid token responses from the FCM backend or max registered time 2 month old. Ref: https://firebase.google.com/docs/cloud-messaging/manage-tokens

KRist
  • 1,402
  • 12
  • 10