Sub topic 14
Storing and maintaining tokens on your server
This chapter covers how your backend keeps a correct, current list of FCM registration tokens. It assumes you can already call getToken() and listen to onTokenRefresh, as shown in the chapter on registration tokens. It also assumes you have some form of backend and user sign-in. Any database works for the examples. The ideas do not depend on one.
Why the server needs a copy
A registration token identifies one app installation on one device. FCM does not keep a list of "all devices for user 42". To send a message to a person, your server must know which tokens belong to that person. The server therefore stores a mapping from your own identifiers (user ID, device) to FCM tokens.
If the stored copy is wrong, messages go to the wrong place or nowhere. Most delivery bugs that are not caused by payload or permission problems come from stale or misattributed tokens.
What can change a token
A token is not permanent. The server copy becomes out of date when any of these happens:
- The user reinstalls the app, or restores it on a new device.
- The user clears app data (on Android).
- The app is restored from a backup onto another device.
- FCM rotates the token, for example after a security event or a long period without use.
- You call
deleteToken(), for example at sign-out. - The app has not connected to FCM for a long time. FCM treats the token as expired, and sends to it fail.
Because of this, treat the token as a value you must keep re-synchronizing, not as something you save once.
A data model for tokens
Store one row per installation, not one token column on the user. A user can have a phone, a tablet and a web client at once.
| Column | Purpose |
|---|---|
| `token` | The FCM token. Make it unique. |
| `user_id` | The signed-in user who owns this installation right now. |
| `platform` | `android`, `ios` or `web`. Useful for per-platform payloads and debugging. |
| `app_version` | Helps you find problems that affect only some releases. |
| `updated_at` | When the app last confirmed the token. Used to expire old rows. |
| `created_at` | When the row was first inserted. |
Making token the unique key matters. If a second user signs in on the same device, the same token appears again. An upsert on token moves ownership to the new user, so the previous user stops receiving that person's notifications.
Uploading tokens from the app
The app is responsible for three moments: after sign-in, when the token refreshes, and at sign-out. The sketch below uses a small repository class. The TokenApi interface stands in for your own HTTP or SDK client, so you can replace it without changing the logic.
import 'dart:async';
import 'dart:io' show Platform;
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
abstract class TokenApi {
Future<void> upsertToken({
required String token,
required String platform,
required String appVersion,
});
Future<void> removeToken(String token);
}
class TokenSync {
TokenSync(this._api, this._messaging, {required this.appVersion});
final TokenApi _api;
final FirebaseMessaging _messaging;
final String appVersion;
StreamSubscription<String>? _refreshSub;
String get _platform {
if (kIsWeb) return 'web';
return Platform.isIOS ? 'ios' : 'android';
}
/// Call after the user signs in and notification permission is settled.
Future<void> start() async {
final token = await _messaging.getToken();
if (token != null) {
await _upload(token);
}
await _refreshSub?.cancel();
_refreshSub = _messaging.onTokenRefresh.listen(_upload);
}
Future<void> _upload(String token) async {
try {
await _api.upsertToken(
token: token,
platform: _platform,
appVersion: appVersion,
);
} catch (e) {
debugPrint('Token upload failed: $e');
}
}
/// Call before the user signs out, while the auth session is still valid.
Future<void> stop() async {
await _refreshSub?.cancel();
_refreshSub = null;
final token = await _messaging.getToken();
if (token != null) {
try {
await _api.removeToken(token);
} catch (e) {
debugPrint('Token removal failed: $e');
}
}
await _messaging.deleteToken();
}
}A few details in this code are deliberate:
start()runs after sign-in, so the server can attach the token to an authenticated user. Uploading before sign-in would create rows with no owner.- The refresh listener reuses the same upload function. A refreshed token is just another upsert.
stop()removes the row first, while the auth session still works, and only then callsdeleteToken(). If you sign out first, the removal request may be rejected.deleteToken()invalidates the token on FCM's side. The nextgetToken()produces a fresh one, so the next user on that device gets a different token.
Also refresh periodically
onTokenRefresh does not cover every case. A reinstall produces a new token without any refresh event on the old one. A failed upload on a bad network is lost unless you retry. A good rule is to call start() on every cold launch, and to upsert again if the stored updated_at is older than about a week. Google recommends refreshing tokens at least monthly. Doing it more often costs one small request.
Cleaning up on the server
The server should assume that some stored tokens are dead. There are two cleanup mechanisms.
React to send errors
When you send through the HTTP v1 API, a dead token produces an error response. Two error codes mean the token should be removed:
UNREGISTERED(HTTP 404): the token is no longer valid. The app was uninstalled, or the token expired.INVALID_ARGUMENT(HTTP 400): the token format is wrong, or the payload is invalid. Inspect the error details. Delete the token only if the details point to the token field. A bad payload would otherwise wipe valid tokens.
Other errors, such as UNAVAILABLE (503) and INTERNAL (500), are temporary. Retry them with exponential backoff and do not delete anything.
This sketch shows the decision in Node.js with the Firebase Admin SDK:
const { getMessaging } = require('firebase-admin/messaging');
const DEAD_TOKEN_CODES = new Set([
'messaging/registration-token-not-registered',
'messaging/invalid-registration-token',
]);
async function sendToUser(db, userId, notification, data) {
const tokens = await db.getTokensForUser(userId); // returns string[]
if (tokens.length === 0) return;
const response = await getMessaging().sendEachForMulticast({
tokens,
notification,
data,
});
const dead = [];
response.responses.forEach((result, i) => {
if (!result.success && DEAD_TOKEN_CODES.has(result.error?.code)) {
dead.push(tokens[i]);
}
});
if (dead.length > 0) {
await db.deleteTokens(dead);
}
}sendEachForMulticast accepts up to 500 tokens per call and returns one result per token, in the same order as the input. That ordering lets you match each failure to its token by index.
Expire by age
Not every dead token produces an error you will see, because you may never send to it. Run a scheduled job that deletes rows whose updated_at is older than your expiry window. FCM considers a token inactive after 270 days without a connection, so that is a safe upper bound. A shorter window, such as 60 days, keeps the table smaller and the send lists shorter. The cost is that a user who returns after a long absence has no token until the app starts again and uploads one. That is normally fine, because the app uploads on launch.
Edge cases
- Shared devices. The unique key on
tokenplus an upsert moves the token to whoever signed in last. Without it, the previous user keeps receiving messages meant for them on someone else's phone. Removing the token at sign-out closes the remaining gap. - Multiple tokens per user. Send to all of a user's tokens. Expect some to fail, and handle each failure independently.
- Race on refresh. If a refresh event arrives while the user is signed out, the upload should be rejected or ignored by the server. Cancel the subscription in
stop(), as shown above. - Permission revoked. The token may stay valid even after the user turns notifications off in system settings. Sends can succeed at the FCM level while nothing appears. You can record the permission state alongside the token if you need to know.
- Topic subscriptions. Topic memberships belong to a token. When a token is replaced, the new one is not subscribed. Re-subscribe after a refresh if your app relies on topics.
- Privacy. A token is an identifier tied to a user. Treat it as personal data. Delete it when the account is deleted.
Checklist
- Store one row per installation with a unique
token. - Upsert on sign-in, on every cold launch, and on
onTokenRefresh. - Remove the row and call
deleteToken()at sign-out. - Delete tokens on
UNREGISTERED, and retry temporary errors. - Run a scheduled job that removes rows past your expiry window.
Exercise
A user signs out of your app on a shared tablet, and a second user signs in. Name two things the first user's session should do at sign-out, and the database feature that stops the first user from still receiving notifications if sign-out cleanup fails.
Show answer
At sign-out, the app should delete the token row on the server (while the auth session is still valid) and call FirebaseMessaging.instance.deleteToken() so the next user gets a new token. If cleanup fails, a unique constraint on the token column combined with an upsert makes the token's owner switch to the second user when they sign in and upload the same token.
Exercise
Your server receives a 400 INVALID_ARGUMENT response when sending to one token. Should you delete that token immediately? Explain.
Show answer
No. INVALID_ARGUMENT can mean the token is malformed, but it can also mean the payload is invalid, for example a data value that is not a string. Read the error details. Delete the token only if they point at the token field. Otherwise fix the payload, or every token would be removed for the same mistake.