Introduction
NestJS is a powerful Node.js framework for building efficient server-side applications, while Firebase offers tools like Firebase Cloud Messaging (FCM) for sending notifications. Integrating Firebase with NestJS allows you to send real-time notifications easily.
Prerequisites
Make sure you have:
- β Node.js and npm installed
- β Basic knowledge of NestJS
- β A Firebase project set up
Step-by-Step Guide
Step 1: Create a NestJS Project ποΈ
npm i -g @nestjs/cli
nest new nest-firebase-notifications
cd nest-firebase-notifications
Step 2: Install Firebase Admin SDK π¦
npm install firebase-admin --save
Step 3: Initialize Firebase in NestJS π₯
Create a firebase.service.ts
:
// firebase/firebase.service.ts
import { Injectable } from '@nestjs/common';
import * as admin from 'firebase-admin';
import { ServiceAccount } from 'firebase-admin';
@Injectable()
export class FirebaseService {
constructor() {
const serviceAccount: ServiceAccount = {
projectId: process.env.FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
};
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
async sendNotification(token: string, payload: admin.messaging.MessagingPayload) {
try {
await admin.messaging().sendToDevice(token, payload);
} catch (error) {
console.error('Error sending notification:', error);
}
}
}
Step 4: Add Environment Variables π
Create a .env
file:
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_CLIENT_EMAIL=your-client-email
FIREBASE_PRIVATE_KEY=your-private-key
Load these in your main.ts
:
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [ConfigModule.forRoot()],
...
})
export class AppModule {}
Step 5: Create a Notifications Controller π²
// notifications/notifications.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { FirebaseService } from '../firebase/firebase.service';
@Controller('notifications')
export class NotificationsController {
constructor(private readonly firebaseService: FirebaseService) {}
@Post()
async sendNotification(@Body('token') token: string, @Body('message') message: string) {
const payload = {
notification: {
title: 'New Notification',
body: message,
},
};
await this.firebaseService.sendNotification(token, payload);
return { success: true };
}
}
Step 6: Register the Service and Controller π
Update your app.module.ts
:
import { Module } from '@nestjs/common';
import { NotificationsController } from './notifications/notifications.controller';
import { FirebaseService } from './firebase/firebase.service';
@Module({
imports: [],
controllers: [NotificationsController],
providers: [FirebaseService],
})
export class AppModule {}
Step 7: Test Your Setup π οΈ
Start your app:
npm run start
Test the endpoint with Postman or curl:
curl -X POST http://localhost:5000/notifications \
-H "Content-Type: application/json" \
-d '{
"token": "recipient-device-token",
"message": "Hello from Harsh Shah!"
}'
π Your device should receive a notification!
Conclusion
Integrating Firebase with NestJS for notifications is straightforward. Follow these steps to enhance your application with real-time notifications and improve user engagement. π
Top comments (0)