How to setting up NestJS on Firebase Cloud

How to setting up NestJS on Firebase Cloud

NestJS Firebase Cloud . The following snippet demonstrates two different techniques for setting up NestJS on Firebase Cloud Functions.

Option A - Point a Function to Nest

The first setup modifies the functions configuration to use the Nest **/dist** output, as opposed to the default functions directory. This option is ideal if you have an existing Nest app.

Step 1 - Create Nest App

nest generate app server

Step 2 - Add Functions

Add functions, then delete the automatically generated directory.

npm i -g firebase-tools
firebase init functions


rm -rf functions 

Now update the firebase config to point to the nest app.

 "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run build"
    ],
&nbsp; &nbsp; "source": "server" // <-- here
&nbsp; }
}

firebase.json

Step 3 - Install Dependencies

cd server
npm i firebase-functions firebase-admin express @nestjs/platform-express

Step 4 - Update the package.json

Add the following lines to your package.json.

{
&nbsp; // ...
&nbsp; "main": "dist/index.js",
&nbsp; "engines": {
&nbsp; &nbsp; "node": "8"
&nbsp; }
}

Step 5 - Export the Server

Create a new file named **src/index.ts** that creates an exress app and wraps it with Nest.

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

const server = express();

export const createNestServer = async (expressInstance) => {
&nbsp; const app = await NestFactory.create(
&nbsp; &nbsp; AppModule,
&nbsp; &nbsp; new ExpressAdapter(expressInstance),
&nbsp; );


&nbsp; return app.init();
};

createNestServer(server)
&nbsp; &nbsp; .then(v => console.log('Nest Ready'))
&nbsp; &nbsp; .catch(err => console.error('Nest broken', err));


export const api = functions.https.onRequest(server);

Step 6 - Build, Serve, Deploy

npm run build
firebase serve --only functions
firebase deploy --only functions

Option B - Add Nest to the Functions Source

In this setup, we perform a fresh install of Nest in the Functions source code. This is a good approach if you have existing background functions, but want to wrap Nest as an HTTP function.

Step 1 - Initialize Cloud Functions

Initialize Cloud Functions making sure to choose the TypeScript option.

npm i -g firebase-tools
firebase init functions

Step 2 - Install NestJS

Install Nest. If you have an existing project, also copy over the other dependencies from your Package.json.

cd functions
npm i --save @nestjs/core @nestjs/common rxjs reflect-metadata express @nestjs/platform-express

Step 3 - Add NestCLI Support

One of the best features in Nest is the CLI. Let’s add support by creating the following file:

functions/nest-cli.json

{
&nbsp; &nbsp; "language": "ts",
&nbsp; &nbsp; "collection": "@nestjs/schematics",
&nbsp; &nbsp; "sourceRoot": "src"
&nbsp; }
&nbsp;&nbsp;

Step 4 - Update the TS Config

Nest uses TypeScript features that are not enabled in Cloud Functions by default. Let’s change that.

functions/tsconfig.json

{
&nbsp; "compilerOptions": {
&nbsp; &nbsp; "module": "commonjs",
&nbsp; &nbsp; "noImplicitReturns": true,
&nbsp; &nbsp; "noUnusedLocals": true,
&nbsp; &nbsp; "outDir": "lib",
&nbsp; &nbsp; "sourceMap": true,
&nbsp; &nbsp; "strict": false,
&nbsp; &nbsp; "target": "es2017",
&nbsp; &nbsp; "emitDecoratorMetadata": true,
&nbsp; &nbsp; "experimentalDecorators": true,
&nbsp; &nbsp; "declaration": true,
&nbsp; &nbsp; "removeComments": true,
&nbsp; &nbsp; "baseUrl": "./",
&nbsp; &nbsp; "incremental": true,
&nbsp; &nbsp; "esModuleInterop": true
&nbsp; },
&nbsp; "compileOnSave": true,
&nbsp; "include": [
&nbsp; &nbsp; "src"
&nbsp; ]
}

Step 5 - Generate an App Module

nest generate module app --flat


nest generate controller egg

The file structure of Nest + Cloud Functions

Step 6 - Create the Server

Lastly, create the Nest server and wrap it in a Cloud Function. It’s purpose is to export an ExpressJS app and expose a function that wraps it with Nest.

functions/src/index.ts

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


const server = express();


const createNestServer = async (expressInstance) => {
&nbsp; const app = await NestFactory.create(
&nbsp; &nbsp; AppModule,
&nbsp; &nbsp; new ExpressAdapter(expressInstance),
&nbsp; );


&nbsp; return app.init();
};




createNestServer(server)
&nbsp; &nbsp; .then(v => console.log('Nest Ready'))
&nbsp; &nbsp; .catch(err => console.error('Nest broken', err));


export const api = functions.https.onRequest(server);

Step 7 - Build, Serve, Deploy

cd functions
npm run serve


firebase deploy --only functions

The should give you a URL that looks like [**http://localhost:5000/YOUR-PROJECT/REGION/api/eggs**](http://localhost:5000/YOUR-PROJECT/REGION/api/eggs "**http://localhost:5000/YOUR-PROJECT/REGION/api/eggs**") where you can start testing the API. Happy Nesting 🥚🥚🥚!

Recommended Reading

Building a Node.js App with TypeScript Tutorial

How to Role-Based Access Control in a Node.js application

How to Build Node.js Modules with Rust

Node.js Tutorial for Beginners in 2020

Introduce to Mutation and Database Access in GraphQL

node-js javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Hands on with Node.Js Streams | Examples & Approach

The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.