Firebase Cloud Messaging (FCM) is quite often being used to send push notification to customers. Google has excellent documentation and you can find tons of examples out there to get you started.
But I did not find many discussions about how to update the device tokens. In the real world, it is very important to maintain the tokens up-to-dated as tokens could change over time.
As we know saving user’s device tokens is the prerequisite to be able to send push notification. A user can have more than one token (for example using 2 devices) so it’s important to ensure that we store all tokens in the database. A token arrays could be maintained in the backend database and being used when sending push notification to devices:
// Node.js
var admin = require('firebase-admin');
// ownerId - who owns the picture someone liked
// userId - id of the user who liked the picture
// picture - metadata about the picture
async function onUserPictureLiked(ownerId, userId, picture) {
// Get the owners details
const owner = admin.firestore().collection('users').doc(ownerId).get();
// Get the users details
const user = admin.firestore().collection('users').doc(userId).get();
await admin.messaging().sendToDevice(
owner.tokens, // ['token_1', 'token_2', ...]
{
data: {
owner: JSON.stringify(owner),
user: JSON.stringify(user),
picture: JSON.stringify(picture),
},
},
{
// Required for background/quit data-only messages on iOS
contentAvailable: true,
// Required for background/quit data-only messages on Android
priority: 'high',
},
);
}
The admin.messaging().sendToDevice
will return an object that contains the result of messaging delivery result, including success count and failure count, as well as the result for each token in the results array:
{
successCount: 1,
failureCount: 1,
canonicalRegistrationTokenCount: 0,
multicastId: 955052197873664600,
results: [
{ messageId: '1642701659970999' },
{
error: {
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.'
}
},
]
}
By examining this returned result of admin.messaging().sendToDevice
we can easily keep user’s tokens up-to-dated. Below is a simple code snippet.
async function updateTokens(
tokens: string[],
res: admin.messaging.MessagingDevicesResponse,
userId: string
) {
if (res.failureCount > 0) {
res.results.forEach((result, index) => {
if (result.error) {
tokens.splice(index, 1)
}
})
await db.collection('users').doc(userId).set(
{
tokens
},
{ merge: true }
)
}
}
I hope you find this short article helpful.