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.

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
{
"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

index.js
Create an express GET endpoint called /hello.
const express = require('express');
exports.app = functions.https.onRequest(app);
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);
});
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.

Choose you plan based on your project needs.

Create Firebase Project

You can disable if you don't want analytics.

If yes choose analytics projects.

Navigate to Functions and follow the instructions.

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

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.

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

Project Type
We are using JavaScript for the project.

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


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

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

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

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');
Included console logs for tracking issues. 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);
Firebase Deploy
This will execute functions directory files.

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

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

Fail Response

Wrong Request Input

Function Logs
You will find the logs to debug the issues.

hello tamada,
ReplyDeleteI 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.
This only works on US region.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDelete