DEV Community

Cover image for How to Integrate Firebase in NestJS for Notifications 🚀
Harsh Shah
Harsh Shah

Posted on

How to Integrate Firebase in NestJS for Notifications 🚀

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
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Firebase Admin SDK 📦

npm install firebase-admin --save
Enter fullscreen mode Exit fullscreen mode

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);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Load these in your main.ts:

import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [ConfigModule.forRoot()],
  ...
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

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 };
  }
}
Enter fullscreen mode Exit fullscreen mode

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 {}
Enter fullscreen mode Exit fullscreen mode

Step 7: Test Your Setup 🛠️

Start your app:

npm run start
Enter fullscreen mode Exit fullscreen mode

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!"
}'
Enter fullscreen mode Exit fullscreen mode

🎉 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)