A Comprehensive Guide on Integrating Firebase with Nest JS

A Comprehensive Guide on Integrating Firebase with Nest JS

Nest JS has become a popular backend framework. However, there is a lack of good articles or guides on how to integrate Nest JS with Firebase, specifically using Firebase Functions Gen 2. Therefore, I have decided to compile my own guide to explore this topic.

This article walks you through creating a basic NestJS function using Firebase Generation 1 and then upgrading it to Generation 2.

Generation 1 functions used Node 16 and had several issues that were incrementally solved by Firebase. Therefore, it is recommended to use Generation 2 cloud functions instead, as Generation 2 offers improved features and stability.

Here are the salient features of Generation 2:


  • Longer request processing times
  • Larger instance sizes
  • Improved concurrency
  • Traffic management
  • Eventarc integration
  • Broader CloudEvents support
  • Support for Node v20

Step 1 : Setup Firebase CLI

Open the terminal and install the Firebase CLI globally on your system using the following command:

npm install -g firebase-tools         

For example :

Step 2 : Creating a firebase project

Navigate to https://firebase.google.com/ using your Google account, and click on the "get started" button.

Here, Firebase will guide you through a two-step process. First, Firebase will ask for the project name. Then, it will inquire whether you want to enable Google Analytics and testing. For now, you can choose to keep them off.

Step 3 : Upgrade from spark package to Firebase Blaze

By default, your new project will be on the spark package. To use Firebase functions, you will need to upgrade it to the blaze package.

Step 4 : Setup nest js project

To begin, we will install the Nest.js CLI on our system.

npm i -g @nestjs/cli         

For example :

Now, we will create a demo Nest.js project.

nest new demo-project         

For example :

After this run these two commands

cd demo-project 
npm run start:dev         

You will see a nest js project as


This is a basic NestJS project with no functions or Firebase integration. I opened my project directory in VS Code, and we can see the project structure as follows:

As you can see, we have a main.ts file with a function that listens on port 3000. To see the "Hello World" message in your browser, navigate to https://localhost:3000/.

If you encounter an error, make sure that your Nest.js project is running And you have written "http" in your URL instead of "https".

To run nest JS project :

npm run start:dev        

For better testing, we can use Postman instead of a browser.

Step 5 : Install Postman

To install Postman on your system, follow these steps:


  1. Go to https://www.postman.com/.
  2. Download and install Postman.
  3. Once installed, run your Nest JS project.
  4. Open Postman and enter https://localhost:3000/ to see the results.


Step 6 : Install firebase functions

Now it's time to install Firebase Functions within our Nest.js project. First, we need to log in to Firebase using the Firebase CLI.

While being in the root of your project directory, run the following command:

firebase logout         

This will log you out of Firebase if you were already logged in. Then, run the following command:

 firebase login         

as shown

Now run this command, and make sure to choose the 'existing project' option when prompted by the Firebase CLI:

 firebase init functions         

Here, I am selecting the 'demo' project that I created on my Firebase console. After this, you will be prompted for some options. Please select the following:

Your updated project structure looks like this now

Run this command to remove the "functions" directory because we will be using functions from the Nest JS project instead of the Firebase Functions folder.

rm -rf functions/        

After this run the following commands to install necessary dependencies.

npm i firebase-admin firebase-functions express @nestjs/platform-express
npm i firebase-functions-test npm-run-all --save-dev        

Update the contents of firebase.json file to

{
  "functions": [
    {
      "source": ".",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log"
      ],
      "predeploy": [
        "npm --prefix \\"$RESOURCE_DIR\\" run lint",
        "npm --prefix \\"$RESOURCE_DIR\\" run build"
      ]
    }
  ]
}         

Here we have set the source to "." which means we are telling Firebase to check functions at the project root. Now, add the following to your package.json file.

"engines": {
    "node": "20"
  },
  "main": "dist/index.js",         

This will instruct Firebase to use Node version 20 and set the index file as the entry point for the project. Please note that the current entry point for the project is a file named "main.ts", so we will rename it to "index.ts".

Next, update the "scripts" section of the package.json file with the following configuration:

"scripts": {
    "build:watch": "tsc --watch",
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log",
    "build": "nest build",
    "format": "prettier --write \\"src/**/*.ts\\" \\"test/**/*.ts\\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/index",
    "lint": "",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },         

Now update the index.ts file to

// Import necessary modules
import {NestFactory} from '@nestjs/core';
import {ExpressAdapter, NestExpressApplication} from '@nestjs/platform-express';
import * as express from 'express';
import * as functions from 'firebase-functions';
import {AppModule} from './app.module';

// Create an Express server
const server: express.Express = express();

?// Define a function to create a NestJS server within an Express instance
export const createNestServer = async (expressInstance: express.Express) => {
??// Create an ExpressAdapter with the Express instance
??const adapter = new ExpressAdapter(expressInstance);

??// Create a NestJS application using the AppModule and the adapter
??const app = await NestFactory.create<NestExpressApplication>(
????AppModule, adapter, {},
??);

??// Enable CORS for the application
??app.enableCors();

??// Initialize the application and return it
??return app.init();
};

// Create the NestJS server and log the status
createNestServer(server)
??.then(v => console.log('Nest Ready')) // Log success message
??.catch(err => console.error('Nest broken', err)); // Log error message

// Export the Express server as a Firebase cloud function
export const api: functions.HttpsFunction = functions.https.onRequest(server);         

Install firebase-functions with command

npm i firebase-functions         

Once done update the nest-cli.json file to

{
  "$schema": "<https://json.schemastore.org/nest-cli>",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "deleteOutDir": true
  },
  "entryFile": "index"
}         

Here, we are informing Nest JS that the entry point is an index.ts file located in the src/ folder.

Step 7 : Run Nest JS Firebase Functions locally

Now lets start the project. Run the command

npm run serve         

This will start firebase cloud functions locally on your system

Copy this URL and lets test it in Postman.

Here your nest js function is returning correct data as a firebase function.

Step 8 : Deploy the function to firebase

Run the command

 npm run deploy         

This will essentially execute the firebase deploy --only functions command, which you can find in your package.json file.

After a successful deployment, your terminal will resemble something like this:

Here, Firebase has provided two URLs. The URL at the top is the deployed Gen 1 API endpoint of our Nest JS project. The URL below is the project URL, where you can navigate to see the deployment. To access the Firebase console, go to the "functions" section.

Here you can see your deployed function and its URL

Something like this

Do notice that its a v1 function that means its a Gen 1 function.

Step 9 : Test Gen 1 function

Now if you hit the function URL in your postman or browser you will get an error.

Currently, your function is not publicly accessible. To fix this, follow these steps:


  1. Navigate to https://console.cloud.google.com/functions/list
  2. Select your function name, which in this case is api.
  3. Go to permissions.
  4. Add a new permission as follows:


Now anyone can access your API URL. Please retry your function URL (the one shown in your Firebase console) in Postman. This will be the result.

We have successfully deployed our NEST JS Firebase Cloud Function and made it publicly accessible.

Step 10 : Upgrade to Gen 2 function, deploy and test

Update your index.ts file to this. Code has comments explaining the logic

import { NestFactory } from '@nestjs/core';
import {
  ExpressAdapter,
  NestExpressApplication,
} from '@nestjs/platform-express';
import * as express from 'express';

// Import Gen 2 library
import { onRequest } from 'firebase-functions/v2/https';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

// Create a new express server
const expressServer = express();

// Include the compression middleware
const compression = require('compression');

// Define an asynchronous function to initialize a NestJS module
const apiFunction = async (expressInstance): Promise<void> => {
  // Create a new Nest application instance
  const api = await NestFactory.create<NestExpressApplication>(
    AppModule,
    new ExpressAdapter(expressInstance),
  ); // Use the compression middleware

  api.use(compression()); // Use the validation middleware

  api.useGlobalPipes(new ValidationPipe({ transform: true })); // Enable CORS

  api.enableCors({}); // Initialize the api

  await api.init();
};

// Export a Firebase function that initializes the API function and then passes the request and response to the express server
export const api = onRequest(async (request, response) => {
  await apiFunction(expressServer);
  expressServer(request, response);
});         


Now, install any missing dependencies using npm. For example, run 'npm i compression' to install the compression package.

Next, it's time to test our Gen 2 / v2 function. Run the following command:

npm run serve         

If no errors occur, then your gen 2 function is ready to be deployed to Firebase.

Please note that the Firebase console currently cannot automatically upgrade gen 1 to gen 2. Therefore, you need to go to the Firebase console website and delete your gen 1 API function.

Next, ensure that you are at the root of your project on your system. Then, run the following command in the terminal:

npm run deploy         

Firebase is now deploying a Gen 2 function.

As you can see, the function URL is quite different. Now navigate to your Firebase console.

Here, you can see that your function is now a Gen 2 / v 2

By default, the gen2 functions are public. If you test this URL in Postman, you will see a successful result of "Hello World".

All done. We have successfully integrated Firebase into a Nest.js project. We then deployed both Gen 1 and Gen 2 versions and tested them.

Ay?e Nur Aslan

Bilgisayar Mühendisi

1 周

It was very useful and explanatory for me. Thank you :)

要查看或添加评论,请登录

社区洞察

其他会员也浏览了