Deploy NodeJS Express Application to Firebase as Function.
Wall Script
Wall Script
Monday, June 22, 2020

Deploy NodeJS Express Application to Firebase as Function.

Few days back I posted an article about how to implement restful apis using the Node Express and MySql. In this post I am going to discuss deploying NodeJS RESTful apis with Express framework to the Firebase functions. This is helpful when you deal with external endpoints which need secret keys. Google Firebase functions as an alternate product for Amazon Lambda, and Google Firebase is offering Storage and Real-time databases.

Node Express Firebase Functions


Live Demo

Video Tutorial


Initialize NodeJS
Create a project folder and initialize Node project.
$npm init

This will generate a package.json with product information. Give starting file as index.js.

{
"name": "node-express-firebase",
"version": "1.0.0",
"description": "Node express firebase functions",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/srinivastamada/node-express-firebase.git"
},
"keywords": [
"Node",
"Express",
"Firebase",
"Restful"
],
"author": "Srinivas Tamada",
"license": "ISC",
"bugs": {
"url": "https://github.com/srinivastamada/node-express-firebase/issues"
},
"homepage": "https://github.com/srinivastamada/node-express-firebase#readme"
}


Is this OK? (yes) y

Install Dependancies
You have to following Node dependencies to improve the project.

Express
Express is a web application framework, that provides restful endpoints.
npm install express

Nodemon
Nodemon is a tool that helps to run Node application continuously.
npm install nodemon

Body-Parser
Body-parser is a middleware tool that helps to parse incoming request bodies in a middleware before your handlers, available under the req.body property.
npm install body-parser

.gitignore
Create an ignore file for Git and exclude node_modules.
/node_modules

.prettierrc
Prettier configuration file. Here I have enabled singleQuote value true
{
"singleQuote": true
}

Node Project Structure
Firebase Initiate

index.js
Create an express GET endpoint called /hello.
const express = require('express');
const PORT = 3000;
const app = express();

/* JSON body parse*/
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/hello', (req, res, next) => {
console.info('/hello call success ');
res.send('Welcome to Firebase Cloud Functions');
});

app.listen(PORT, () => {
console.info('Server is running on PORT:', PORT);
});
exports.app = functions.https.onRequest(app);

Run Project
You can test the project at http://localhost:3000/hello.
$nodemon index.js

Working with Firebase
Choose Google Firebase free plan. Firebase has premium paid plans

Free plan has offering 125K free requests per month.
Firebase Initiate

Choose you plan based on your project needs.
Firebase Initiate

Create Firebase Project
Firebase Initiate

You can disable if you don't want analytics.
Firebase Initiate

If yes choose analytics projects.
Firebase Initiate

Navigate to Functions and follow the instructions.
Firebase Initiate


Firebase Tools
Express is a web application framework, that provides restful endpoints.
npm install -g firebase-tools
Firebase Initiate


Firebase Login
Use the following command and login with your Google account.
firebase login

Firebase Initiate
Now go to project folder and initiate Firebase.
firebase init

Select Functions.
Firebase Initiate


Select Firebase Project
Use arrow buttons and select the particular project.
Firebase Initiate

Project Type
We are using JavaScript for the project.
Firebase project type

NPM Dependancies
This will create some configuration files and says yes for NPM dependencies.
Firebase project type

Firebase project type

Firebase Project Structure
This will create a functions directory with same index.js source code. But including Firebase libraries.
Firebase project type

Firebase Serve
Run Firebase functions project. You can delete the main index.js.
Firebase project type

Like previous this will run at port 3000 for local testing.
Firebase project type

functions/index.js
Modified Firebase index.js. You can enhance the project here. Added a post method to validate email input using email-validator plugin. Make sure use NPM package install commands inside functions directory.
const functions = require('firebase-functions');
const express = require('express');
const validator = require("email-validator");
const PORT = 3000;
const app = express();

/* JSON body parse*/
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/hello', (req, res, next) => {
console.info('/hello call success ');
res.send('Welcome to Firebase Cloud Functions');
});

app.post('/emailValidate', async (req, res, next) => {
const postData = req.body;
if(postData.email){
console.info('/emailValidate call success ');
res.json({'status': validator.validate(postData.email) });
} else {
console.warn('/emailValidate wrong input ');
res.status(500).json({'status': 'wrong input'});
}
});

app.listen(PORT, () => {
console.info('Server is running on PORT:', PORT);
});

exports.app = functions.https.onRequest(app);

Included console logs for tracking issues.

Firebase Deploy
This will execute functions directory files.
Firebase project type

Now go to Firebase console and you will find the endpoint url.
Firebase project type

GET URL
Use GET endpoint directly.
https://us-central1-node-express-ea766.cloudfunctions.net/app/hello

POST Methods
Use Postman tool and validate the response.

Success Response
Firebase project type

Fail Response
Firebase project type

Wrong Request Input
Firebase project type

Function Logs
You will find the logs to debug the issues.
Firebase project type
web notification

3 comments:

  1. hello tamada,
    I am error after deploy my script in firebase.
    Error: Forbidden
    Your client does not have permission to get URL /api/user from this server.
    please help me.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete

mailxengine Youtueb channel
Make in India
X