DEV Community

Cover image for How to Integrate Firebase in NestJS for Notifications πŸš€
Harsh Shah
Harsh Shah

Posted on

3

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. πŸš€

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more