如何在NestJS服务器中使用FCM推送通知?求教程及参考链接
在NestJS中集成FCM推送通知的实现流程
1. 确认依赖安装
虽然你已经完成Firebase与NestJS的连接,仍需确保firebase-admin依赖已正确安装:
npm install firebase-admin # 或使用 yarn yarn add firebase-admin
2. 封装FCM推送服务
在项目中创建专用的FCM服务(比如src/notifications/fcm.service.ts),将推送逻辑封装为可复用的方法:
import { Injectable } from '@nestjs/common'; import { getMessaging } from 'firebase-admin/messaging'; import { getApp } from 'firebase-admin/app'; @Injectable() export class FcmService { private messaging = getMessaging(getApp()); // 向单个设备推送通知 async sendToSingleDevice( deviceToken: string, title: string, body: string, data?: Record<string, string>, ) { const payload = { notification: { title, body }, token: deviceToken, ...(data && { data }), }; try { return await this.messaging.send(payload); } catch (error) { // 可根据Firebase错误码做针对性处理(比如无效token、设备未注册) console.error('FCM单推失败:', error); throw error; } } // 向多设备批量推送(单次最多支持1000个token) async sendToMultipleDevices( deviceTokens: string[], title: string, body: string, data?: Record<string, string>, ) { const payload = { notification: { title, body }, tokens: deviceTokens, ...(data && { data }), }; try { return await this.messaging.sendEachForMulticast(payload); } catch (error) { console.error('FCM批量推送失败:', error); throw error; } } }
3. 注册FCM服务到模块
将FcmService添加到对应模块的providers数组中,若需跨模块使用记得导出:
import { Module } from '@nestjs/common'; import { FcmService } from './notifications/fcm.service'; @Module({ providers: [FcmService], exports: [FcmService], // 允许其他模块注入该服务 }) export class NotificationsModule {}
4. 在业务逻辑中调用推送服务
比如在控制器中创建接口,触发推送逻辑:
import { Controller, Post, Body } from '@nestjs/common'; import { FcmService } from './notifications/fcm.service'; @Controller('notifications') export class NotificationsController { constructor(private readonly fcmService: FcmService) {} @Post('single') async sendSingleNotification( @Body() body: { token: string; title: string; body: string; data?: Record<string, string> }, ) { const messageId = await this.fcmService.sendToSingleDevice( body.token, body.title, body.body, body.data, ); return { status: 'success', messageId }; } }
实用细节提示
- 字段区别:
notification字段会直接在设备通知栏展示,data字段为自定义键值对,需客户端自行处理(比如点击通知跳转指定页面) - 错误处理:FCM返回的错误码可用于识别问题(如
messaging/invalid-registration-token表示token无效),可据此清理数据库中的无效token - 批量限制:
sendEachForMulticast单次最多支持1000个token,超过需拆分分批推送
内容的提问来源于stack exchange,提问作者Shatha AR
相关产品推荐
相关产品推荐

