Firebase - Remove Obsolete FCM Tokens in Node JS.
Nitesh Sawant
Posted on December 29, 2020
What is FCM ?
Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost.
How FCM is used with Node JS .
- Usually an mobile application or browser registers itself to with FCM and FCM gives that device an unique token.
- The Device then sends this token ton Node JS server.
- Node JS server stores that FCM token in database.
- Now whenever user needs to be notified . Server using package Firebase, Sends push notification to the user.
The Problem
The problem starts to arise when the FCM tokens expire. It can happen in below cases.
- User deletes the app without logging out.
- User dont use the app for long time.
So this Obsolete tokens stays in the database and it takes up the space. In cases where user can log in into multiple devices. In backend if user needs to be notified some action to all the devices , In most of the push notification are triggered to Obsolete tokens.
The Solution
The Solution here is to run a cron job , may be once a week . Send a Dry push notification and check if the tokens throws any error .If there is any error it means the Token is obsolete and we can safety delete the token from database.
The Code
const admin = require("firebase-admin");
const serviceAccount = require(`./google-services.json`);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
// databaseURL: 'https://marioplan-17d32.firebaseio.com'
});
const verifyToken = async (token) => {
const message = {
data: {
score: "850",
time: "2:45",
},
token,
};
return admin.messaging().send(message, true);
};
const allTokens = await allTokensFromDB();
for (let index = 0; index < allTokens.length; index++) {
const element = allTokens[index];
const { id, token } = element;
try {
await verifyToken(token);
} catch (error) {
if (
error.code === "messaging/registration-token-not-registered" ||
error.code === "messaging/invalid-argument"
) {
await deleteTokenFromDB(id);
}
}
}
Run Above code Snippet as CRON job.
Posted on December 29, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.