How to send push notification with firebase cloud messaging in Nest Js using device token

     For Push Notification firebase is one of the most simple and useful tool. you can send notification to particular device using their token Id. this article show the simple way to send push notification.

first of all install firebase-admin. 

npm i firebase-admin
It bypasses the security rules of your Firebase Database. It also has functionality to manage users and mint custom tokens and can be used to send FCM messages.

1. Go to firebase console and create firebase application
2. After creating application go to application > click setting Icon > Project Settings
3. In project settings go to service account
4. Generate New private key
This generate new private key button generate JSON file. this is used to authenticate a service account and authorize it to access Firebase services.

5. Create new nest js application
6. Past this firebase configuration file into a nest dir.
main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as admin from 'firebase-admin';
import * as dotenv from 'dotenv';
import * as serviceAccount from "./fb.json"
dotenv.config();

import { NestApplicationOptions } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  try {
    admin.initializeApp({
  credential: admin.credential.cert(JSON.parse(JSON.stringify(serviceAccount)))
});
  } catch (e) {
    console.log('connection failed',e);
  }
  await app.listen(3000);
}
bootstrap();
notification.service.ts
import { Injectable } from '@nestjs/common';
import * as admin from 'firebase-admin';

@Injectable()
export class NotificationService {
  constructor() {}
  async send() {
    const registrationToken ="TOKEN_KEY";
    const message = {
      notification: {
        title: "new test",
        body: "enter_message_here"
            },
      token: registrationToken
    };

    admin.messaging().send(message)
      .then((response) => {
        console.log('Successfully sent message:', response);
      })
      .catch((error) => {
        console.log('Error sending message:', error);
      });
    return 'this is notification';
  }
}
THANK YOU!