How to Integrate Firebase in NestJS for Notifications 🚀
Tags: firebase, nestjs, notification, android
Published: 2024-06-03 18:30:00

#### 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 🏗️**

```bash
npm i -g @nestjs/cli
nest new nest-firebase-notifications
cd nest-firebase-notifications
```

**Step 2: Install Firebase Admin SDK 📦**

```bash
npm install firebase-admin --save
```

**Step 3: Initialize Firebase in NestJS 🔥**

Create a `firebase.service.ts`:

```typescript
// 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:

```plaintext
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_CLIENT_EMAIL=your-client-email
FIREBASE_PRIVATE_KEY=your-private-key
```

Load these in your `main.ts`:

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

@Module({
  imports: [ConfigModule.forRoot()],
  ...
})
export class AppModule {}
```

**Step 5: Create a Notifications Controller 📲**

```typescript
// 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`:

```typescript
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:

```bash
npm run start
```

Test the endpoint with Postman or curl:

```bash
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. 🚀