Host a dynamic website on Google Firebase using Node.js and Cloud Firestore DB | by Tushar Chand Kapoor | Towards Data Science

Tushar Kapoor: (https://www.tusharck.com/)
Demo Git URL: https://github.com/tusharck/firebase-demo
Firebase is a comprehensive app platform built on Google’s infrastructure, therefore it provides a secure, fast, free (paid options also available for additional resources) and easy way to host your content on the web or mobile applications.
It gives free Custom domain & SSL (SSL provides a standard security layer for https connections.Cloud Firestore: A flexible and scalable database for realtime data sync across client apps.Other Features: Cloud Functions, Cloud Messaging (FCM), Crashlytics, Dynamic Links, Hosting, ML Kit, Storage, Performance Monitoring, Predictions and Test Lab (The functionality and resources of these products can be increased by buying a paid plan, but the free tier services are very good. To look at the plans check Firebase Pricing).Automatic scaling of resources.
It gives free Custom domain & SSL (SSL provides a standard security layer for https connections.
Cloud Firestore: A flexible and scalable database for realtime data sync across client apps.
Other Features: Cloud Functions, Cloud Messaging (FCM), Crashlytics, Dynamic Links, Hosting, ML Kit, Storage, Performance Monitoring, Predictions and Test Lab (The functionality and resources of these products can be increased by buying a paid plan, but the free tier services are very good. To look at the plans check Firebase Pricing).
Automatic scaling of resources.
1. Google AccountIf you don’t have a Google account, you need to sign up for one. You can do so by going to https://accounts.google.com/SignUp.
2. Node.js and npm
Mac/WindowsYou can download the installer from https://nodejs.org/en/download/.
Linux Follow the steps below to install Node.js: 1. Open a terminal 2. Run the following commands:
sudo apt-get install curlcurl -sL https://deb.nodesource.com/setup_13.x | sudo bash -sudo apt install nodejs
Note: I have used setup_13.x because at the time of the tutorial latest version was 13 you can check the latest release by going to https://nodejs.org/en/.
To check if Node.js and npm are successfully installed run the following commands, which will output the version installed:
node -vnpm -v
3. Firebase-CLI (Command-Line Interface)These are the tools for managing, viewing, and deploying the Firebase projects.
npm install -g firebase-tools
Go to https://firebase.google.com and Sign In from the top right corner.Click on Go to console, from the top right corner.Then click on Create project, as shown below.
Go to https://firebase.google.com and Sign In from the top right corner.
Click on Go to console, from the top right corner.
Then click on Create project, as shown below.
4. The next thing is to enter the name of your project, and press continue.
5. Press continue to enable Google Analytics for your Firebase project (if you don’t want it then check to disable).
6. Select the nearest location for Google Analytics.
7. Click on Create Project, and wait for it load. Then you will see something like below.
Open a command-line/terminal then create and go to a new directory.
Open a command-line/terminal then create and go to a new directory.
mkdir my-firebase-projectcd my-firebase-project
2. To host a website on Firebase login into firebase using the following command. After you run the command a browser window will open asking you to log in to firebase using your Google credentials. Enter the credentials there and Firebase will sign into your system.
firebase login
Now we have to initialize the project that we created on the Firebase console into the system. For doing run the command below.
Now we have to initialize the project that we created on the Firebase console into the system. For doing run the command below.
firebase init
2. Press down key then select two things by pressing the space bar key.
Functions
Hosting
Then press Enter to continue.
3. Then select Use an existing project then press enter.
4. Press enter on the my-firebase-project or the project name you used.
5. Select Javascript and press enter.
6. You can say No to Do you want to use ESLint to catch probable bugs and enforce style?
7. Type Yes for installing the dependencies with npm.
8. Here we have to do two tasks:
You have to select the directory in which your website and assets will reside. By default it is pubic you can press enter to continue or you can change to your desired directory name.
Types Yes for the single-app page so that your dynamic URLs can be redirected to their proper destination.
9. Test the firebase app on your local system by running the following command. Then go to http://localhost:5000 to see your basic website running.
firebase serve --only hosting,functions
You should see something like this below after opening the http://localhost:5000 URL.
10. Close server from the terminal.
Here we will switch inside the functions directory to do so use.
Here we will switch inside the functions directory to do so use.
cd functions
2. Install ExpressIt is a minimal and flexible Node.js web application framework.
npm i express --save
3. Install Handle BarsIt is a templating engine for Node.js used for the dynamic front end of the website.
npm i handlebars --save
4. Install consolidate
npm i consolidate --save
5. Create a folder named views inside functions folder in which we will store all the frontend code.
mkdir views
6. Switch back to the main directory by running the following command:
cd ..
Go to https://console.firebase.google.com/ .Select your project.Select Database from the pane on the left
Go to https://console.firebase.google.com/ .
Select your project.
Select Database from the pane on the left
4. Click on Create Database
5. Select Start in test mode because otherwise you will not able to access the database from your system. We will change this setting once we are done with the development of the website.Then click Next after doing so.
6. Select the location of your Firestore DB.Note: After you set this location, you cannot change it later.
Click on start collection.
Click on start collection.
2. Enter the Collection ID, you can sample for now.
3. Enter the sample data. Enter sample_doc as the Document ID. Enter Heading inside the Field. I like Cloud inside the Value. Then click Save.
We will split the portion into two parts, in the first part, we will see how to fetch the data from Firestore and use in the website. In the second portion, we will see how to submit the form data.
First, we will download the credentials to access Firestore
Go to https://console.firebase.google.com/ .
Go to https://console.firebase.google.com/ .
2. Click on settings from the left pane and go to Project settings.
3. Go to Service accounts and click on Generate new private key.
4. Click on Generate Key, It will give a pop up to download the key. Store the key inside your functions folder of your website.
Open index.js inside the functions folder.
Open index.js inside the functions folder.
2. We need to define some of the libraries that we want to use in our application. These are the same libraries that we installed earlier.
const functions = require('firebase-functions');const express = require('express');const engines = require('consolidate');var hbs = require('handlebars');const admin = require('firebase-admin');
3. Here we set a few things:
Initialize the app using express.
We will set our engine as handlebars.
Then we will tell the express that our front end code is going to be inside the views folder.
const app = express();app.engine('hbs',engines.handlebars);app.set('views','./views');app.set('view engine','hbs');
4. Authorize your application to access your Firestore DB.Note: 1. Change YOUR_SDK_NAME.json with the file you downloaded for credentials to access Firestore.2. Change the database URL to your database URL. To see the URL you can to Settings > Service Account.
var serviceAccount = require("./YOUR_SDK_NAME.json");admin.initializeApp({credential: admin.credential.cert(serviceAccount),databaseURL: "https://myfirebaseproject-bx54dasx3.firebaseio.com"});
5. Function to fetch data from Firestore.
Collection ID is sample.
Document ID is sample_doc.
We defined the above while entering the sample data.
async function getFirestore(){const firestore_con  = await admin.firestore();const writeResult = firestore_con.collection('sample').doc('sample_doc').get().then(doc => {if (!doc.exists) { console.log('No such document!'); }else {return doc.data();}}).catch(err => { console.log('Error getting document', err);});return writeResult}
Note: We use async because we have to wait for the promise operation to be completed between the Database and our website.
6. Create the route and send the result to the front end.
app.get('/',async (request,response) =>{var db_result = await getFirestore();response.render('index',{db_result});});exports.app = functions.https.onRequest(app);
7. Create index.hbs inside the views folder.Note: .hbs is a handelbars file
8. Write this basic HTML code inside index.hbs to see the fetched result.
<html>    <body>      <h1>{{db_result.Heading}}</h1>    </body></html>
Note: {{db_result.Heading}} , db_result is the variable that was passed from the backend. .Heading is the Field inside the document that we defined while entering the data in the Firestore DB.
9. Open firebase.json and change “destination”: “/index.html” to "function":"app".
10. Delete index.html inside the public folder, deleting this is very important. If you don’t delete this it will always pick this file and our backend code will be useless.
11. Test the firebase app on your local system by running the following command. Then go to http://localhost:5000 to see your basic website running.
firebase serve --only hosting,functions
12. Close the server from the terminal.
Here we will insert data from our website into Firestore.
1. Create Another Collection named form_data, in which we will insert the form data.
Note: It will ask you to enter a document as well to create the collection to enter any sample value.
2. Go to http://localhost:5000 after running the command below to test on your local server.
firebase serve --only hosting,functions
3. Add the HTML code to make a sample form inside index.hbs.
<html>    <body><h1>{{db_result.Heading}}</h1><form action="/insert_data" method="post" >     <fieldset>       <legend>Sample Form</legend>       First name:<br>        <input type="text" name="firstname" >        <br>        Last name:<br>        <input type="text" name="lastname">         <br><br>         <input type="submit" value="Submit">        </fieldset>     </form>   </body></html>
action=”/insert_data” is the path that we will define inside our function.
After refreshing the page it should like as in the image shown below.
3. Inside index.js add the code which inserts data into Firestore.
async function insertFormData(request){const writeResult = await admin.firestore().collection('form_data').add({firstname: request.body.firstname,lastname: request.body.lastname}).then(function() {console.log("Document successfully written!");}).catch(function(error) {console.error("Error writing document: ", error);});}
4. Inside index.js define the route to which the HTML form will send a post request.
app.post('/insert_data',async (request,response) =>{var insert = await insertFormData(request);response.sendStatus(200);});
6. Insert some sample data inside the form to test it.
7. After pressing submit you should see the response as OK displayed on the webpage.
8. Go to https://console.firebase.google.com/ then to the Database section. You should see the inserted form data.
We need to change some piece of code which we used for authentication as when you deploy it online Firebase takes care of authentication.
We need to change some piece of code which we used for authentication as when you deploy it online Firebase takes care of authentication.
Inside index.js remove the following code:
var serviceAccount = require("./YOUR_SDK_NAME.json");admin.initializeApp({credential: admin.credential.cert(serviceAccount),databaseURL: "https://myfirebaseproject-bx54dasx3.firebaseio.com"});
Instead inside index.js, insert this into your code:
admin.initializeApp(functions.config().firebase);
Here we are telling Firebase to take authentication information from config that exists when you deploy.
2. On the terminal inside your website directory, run the following command:
firebase deploy
It will take a few minutes, but after it, you should see something like this:
3. Go to the Hosting URL provided by firebase as shown in the image above.
Congrats You are done with hosting a dynamic website on Firebase.
Buy a domain from any provider like GoDaddy or any other as you feel.Go to Hosting from the pane on left.Click on Connect Domain.
Buy a domain from any provider like GoDaddy or any other as you feel.
Go to Hosting from the pane on left.
Click on Connect Domain.
4. Enter the domain Here:
5. Follow the verification instructions.
Disclaimer:
Terms of Service for Firebase ServicesFirebase and its services are a product of Google, nowhere in this article suggests otherwise.This article is meant for education purposes.
Terms of Service for Firebase Services
Firebase and its services are a product of Google, nowhere in this article suggests otherwise.
This article is meant for education purposes.