使用Firebase Admin从Node.js推送通知返回成功但设备未接收
Node.js调用Firebase Cloud Messaging返回成功但设备收不到推送通知
问题背景
已有Node.js项目需向设备发送推送通知,Firebase应用配置完成,控制台发送测试消息正常,但Node.js代码发送时,返回成功响应却无法收到通知。
接口响应信息
Successfully sent notification { responses: [ { success: true, messageId: 'projects/bioter-app/messages/0:1661888947319442%2fcd2f4df9fd7ecd' } ], successCount: 1, failureCount: 0 }
发送消息代码
import { initializeApp, cert } from "firebase-admin/app"; import { messaging } from "firebase-admin"; import path from "path"; export interface IPushNotificacion { token: string, data: { title: string, message: string } } initializeApp({ credential: cert(path.join(__dirname, 'keys', 'bioter-app-firebase-adminsdk-11lci-9e163aab29.json')) }) export const sendMessage = (messages: IPushNotificacion[]) => { if (!messages.length) return messaging().sendAll(messages) .then(response => { console.log(`Successfully sent notification`) console.log(response) }) .catch(err => { console.log('Notification could not be sent ') console.log(err) }) }
排查与解决方案
1. 消息结构不匹配控制台测试消息
你当前的消息仅包含data字段,而Firebase控制台发送的是通知类型消息(带notification字段)。data字段属于自定义数据消息,不会主动触发设备通知栏展示,需要设备端自行处理并构建通知;而notification字段才是直接在通知栏显示的推送内容。
修改消息结构,添加notification字段:
export interface IPushNotificacion { token: string, notification: { title: string, body: string }, data?: { [key: string]: string } }
调用示例:
sendMessage([{ token: "目标设备推送令牌", notification: { title: "测试推送标题", body: "测试推送内容" } }])
2. 设备端消息处理逻辑验证
如果确实需要发送纯data消息,需确认设备端是否正确监听:
- Android:需在
onMessageReceived方法中解析data字段,手动创建通知栏通知 - iOS:后台状态下纯
data消息不会触发通知,需前台监听或搭配notification字段使用
3. 令牌有效性二次验证
尽管接口返回成功,仍可能存在令牌过期/无效的情况,可替换sendAll为sendEachWithRetry,它会自动重试无效令牌,并返回更详细的错误信息(如令牌过期提示)。
4. 服务账号权限检查
确认Firebase Admin SDK使用的服务账号,在Firebase控制台「项目设置-服务账号」中拥有Cloud Messaging Admin权限,避免因权限不足导致消息未实际送达。
内容的提问来源于stack exchange,提问作者Javier salvañá
相关产品推荐
相关产品推荐

