Firebase push notifications from Node.js to web and Expo
Sosifie's Node.js push notification setup, its single-device limit, and proposed fixes for FCM token cleanup, duplicate alerts and Expo support.
Sosifie's Express + Prisma API sends Firebase push notifications to its Next.js web app with admin.messaging().send(). The current code stores one token per user without cleaning up expired tokens, and duplicate alerts can appear. The examples below propose changes to that web setup and add a plan for the Expo app, which doesn't have push yet.
Keep in-app notifications apart from push
An in-app notification is a row in Postgres (type, sender, recipient, post_id, is_read). The bell, the badge and "mark as read" all read that table. A push is just one attempt to deliver to a device, and a failed push must not touch the row.
Tokens deserve their own table too. Sosifie keeps one fcm_token column on User, so logging in on the laptop silently stops push on the phone. A separate table, keyed by the token:
model DeviceToken {
id String @id @default(uuid())
token String @unique
platform String // "web" | "android" | "ios"
provider String @default("fcm") // or "expo"
user_name String
lastSeenAt DateTime @default(now())
createAt DateTime @default(now())
user User @relation(fields: [user_name], references: [user_name], onDelete: Cascade)
@@index([user_name])
}
token is @unique because a token belongs to a browser profile or an app install, not to a person. When two people share a laptop, the later registration has to move the token to the new account.
Register tokens with an upsert
The web client calls Notification.requestPermission(), then getToken(messaging, { vapidKey }), then sends the token to the API. Don't ask for permission on page load. Put it behind a button. And don't console.log the token: the token plus your server credentials is enough to message that device.
The endpoint should upsert, and the app should call it on every start:
router.post('/devices', authMiddleware.verifyToken, asyncHandler(async (req, res) => {
const { token, platform } = registerDeviceSchema.parse(req.body);
const user_name = req.user.user_name;
await prisma.deviceToken.upsert({
where: { token },
create: { token, platform, user_name },
// Same token, maybe a different account now. Also bumps freshness.
update: { user_name, platform, lastSeenAt: new Date() },
});
res.sendStatus(204);
}));
Firebase recommends treating tokens you haven't seen in a while (about a month) as stale. A nightly job can delete rows with an old lastSeenAt. Logout should delete the current device's row.
Sending, and cleaning up dead tokens
An FCM message has notification (the OS shows it when the app isn't open) and data (a flat map you handle yourself). Every value in data must be a string. My first version spread the object in as-is, and the current one runs every value through String(). For the web, the click target goes in webpush.fcmOptions.link, and a tag makes notifications on the same topic replace each other:
import type { MulticastMessage } from 'firebase-admin/messaging';
const toData = (obj: Record<string, unknown>) =>
Object.fromEntries(
Object.entries(obj).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)]),
);
export function buildMessage(n: { id: string; type: string; postId?: string }, title: string, body: string) {
const tag = n.postId ? `post-${n.postId}` : n.type;
return {
notification: { title, body },
data: toData({ id: n.id, type: n.type, post_id: n.postId }),
webpush: {
notification: { tag },
fcmOptions: { link: `${env.WEB_URL}${n.postId ? `/post/${n.postId}` : '/notify'}` },
},
android: { notification: { tag } },
apns: { headers: { 'apns-collapse-id': tag } },
} satisfies Omit<MulticastMessage, 'tokens'>;
}
sendMulticast and sendAll are gone in firebase-admin 13. Use sendEachForMulticast (up to 500 tokens). Its results come back in the same order as the token array, so removing dead tokens is short:
import { getMessaging } from 'firebase-admin/messaging';
const DEAD_TOKEN_CODES = new Set([
'messaging/registration-token-not-registered',
'messaging/invalid-registration-token',
]);
export async function pushToUser(user_name: string, message: Omit<MulticastMessage, 'tokens'>) {
const rows = await prisma.deviceToken.findMany({ where: { user_name, provider: 'fcm' } });
if (rows.length === 0) return;
const tokens = rows.map((r) => r.token);
const res = await getMessaging().sendEachForMulticast({ ...message, tokens });
const dead = res.responses
.map((r, i) => (!r.success && r.error && DEAD_TOKEN_CODES.has(r.error.code) ? tokens[i] : null))
.filter((t): t is string => t !== null);
if (dead.length > 0) await prisma.deviceToken.deleteMany({ where: { token: { in: dead } } });
}
Don't add messaging/invalid-argument to that set. It also shows up when the payload is malformed, and one typo in a field would wipe every token.
The service worker and the foreground listener
The web SDK looks for /firebase-messaging-sw.js at the root, so in Next.js it goes in public/. Mine still loads the version 9 compat scripts while the app is on firebase 12. Its onBackgroundMessage also calls showNotification() for a payload that already has notification, which can show it twice.
In the foreground, the current code wraps onMessage in a Promise and re-subscribes itself, adding a listener per message that is never removed. onMessage returns an unsubscribe function, and a plain effect is enough:
useEffect(() => {
let unsubscribe: (() => void) | undefined;
isSupported().then((ok) => {
if (!ok) return;
unsubscribe = onMessage(getMessaging(app), (payload) => {
const id = payload.data?.id;
if (!id || seen.current.has(id)) return; // the socket may have shown it already
seen.current.add(id);
showToast(payload);
});
});
return () => unsubscribe?.();
}, []);
isSupported() is there because getMessaging() throws in iOS Safari when the web app isn't installed to the home screen.
Expo apps should use Expo push tokens
Sosifie's Expo app doesn't have push yet, so this part is a plan. Since SDK 53, Expo Go on Android no longer supports push, and you need a development build. Android also needs a notification channel first.
On iOS, getDevicePushTokenAsync() returns a raw APNs token, which firebase-admin can't send to unless the app includes the Firebase iOS SDK. Working alone, I'd use getExpoPushTokenAsync() and send through expo-server-sdk, storing those tokens in the same DeviceToken table with provider: 'expo'. A DeviceNotRegistered error in a receipt is the Expo version of a dead FCM token.
export async function registerForPush(): Promise<string | null> {
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('default', {
name: 'Default',
importance: Notifications.AndroidImportance.DEFAULT,
});
}
const { status } = await Notifications.requestPermissionsAsync();
if (status !== 'granted') return null;
const projectId = Constants.expoConfig?.extra?.eas?.projectId ?? Constants.easConfig?.projectId;
const { data } = await Notifications.getExpoPushTokenAsync({ projectId });
await api.post('/devices', { token: data, platform: Platform.OS });
return data;
}
The socket has to go before the push
After writing the row, the API emits new_notification to the recipient's Socket.IO room (as in the real-time chat post), and the client shows a toast and invalidates the query. Right now the code awaits the push before emitting, so a slow FCM call delays the in-app notification too. That order has to flip. An open tab can get the same notification through both paths. The hook above dedupes them on id.
The send path still needs to check the user's mute setting before sending a push. Like/unlike/like again still produces two pushes. That needs dedupe on recipient + sender + type + target within a time window, and only after that comes moving push onto a queue.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.