loading...
Cover image for How to integrate Firebase in NestJS

How to integrate Firebase in NestJS

aswinsanakan profile image Aswin Sanakan ・1 min read

Firebase is a great platform to implement Cloud Functions, Push Notifications, Real-time DBs, and a lot more. Here's how we can integrate Firebase in NestJS.

Install firebase-admin SDK

npm i firebase-admin --save

Initialize the service account

Once you generate private keys from Firebase console (refer here), add it to your ENV file. You can use the @nestjs/config plugin to configure different environments.

FIREBASE_PROJECT_ID=<your_project_id>
FIREBASE_PRIVATE_KEY=<your_private_key>
FIREBASE_CLIENT_EMAIL=<your_client_email>

Configure the firebase instance inside function bootstrap() in main.ts file:

import { NestFactory } from '@nestjs/core';

import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';

// Import firebase-admin
import * as admin from 'firebase-admin';
import { ServiceAccount } from "firebase-admin";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const configService: ConfigService = app.get(ConfigService);
  // Set the config options
  const adminConfig: ServiceAccount = {
    "projectId": configService.get<string>('FIREBASE_PROJECT_ID'),
    "privateKey": configService.get<string>('FIREBASE_PRIVATE_KEY')
                               .replace(/\\n/g, '\n'),
    "clientEmail": configService.get<string>('FIREBASE_CLIENT_EMAIL'),
  };
  // Initialize the firebase admin app
  admin.initializeApp({
    credential: admin.credential.cert(adminConfig),
    databaseURL: "https://xxxxx.firebaseio.com",
  });

  app.enableCors();

  await app.listen(configService.get<string>('API_PORT') || 4000);
}
bootstrap();

NOTE: In the above code, do not forget to add the 'replace' method when fetching the private key. This is because newline characters in Private keys are not properly parsed by dotenv, and needs to be replaced accordingly.

Now, you can import the package in the controller or service to use it:

import * as admin from 'firebase-admin';

...
...

await admin.messaging().sendToDevice(fcmtoken, payload);

That's it, you're good to go!

Posted on by:

aswinsanakan profile

Aswin Sanakan

@aswinsanakan

Web Architect | Software Engineer

Discussion

pic
Editor guide