= Host a dynamic website on Google Firebase using Node.js and Cloud Firestore DB =

Tushar Kapoor: (httpswww.tusharck.com/)
Demo Git URL: httpsgithub.com/tusharck/firebase-demo
= Why Firebase Hosting? =
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

== Key Features and Benefits of free tier: ==
- It gives free Custom domain &
SSL(SSL provides a standard security layer for httpsconnections

- 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

= Steps for hosting your dynamic website on Firebase =
== Requirements ==
**1. Google Account**If you don’t have a Google account, you need to sign up for one. You can do so by going to httpsaccounts.google.com/SignUp. **2. Node.js and npm** Mac/WindowsYou can download the installer from httpsnodejs.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 httpsdeb.nodesource.com/
setup_13.x| sudo bash -sudo apt install nodejs **I have used Note: ** **
setup_13.xbecause at the time of the tutorial latest version was
**13**you can check the latest release by going to httpsnodejs.org/en/

To check if Node.js and npm are successfully installed run the following commands, which will output the version installed:
node -v
npm -v
**3. Firebase-CLI (Command-Line InterfaceThese are the tools for managing, viewing, and deploying the Firebase projects

npm install -g firebase-tools
= Step 1: Create Firebase project =
- Go to httpsfirebase.google.com and
Sign Infrom 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
= Step 2: Initialize Firebase login =
- 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

= Step 3: Initialize Firebase project into your system =
- 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
then press enter

**Use an existing project**
4. Press enter on the
**my-firebase-project** **or the project name you usedor 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
pubicyou can press enter to continue or you can change to your desired directory name

- Types
Yesfor 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
**httplocalhost:5000** to see your basic website running

firebase serve --only hosting,functions
You should see something like this below after opening the
**httplocalhost:5000** URL

10. Close server from the terminal

= Step 4: Installing packages and creating views directory for dynamic website =
- Here we will switch inside the functions directory to do so use

cd functions
**2. Install Express**It is a minimal and flexible Node.js web application framework

npm i express --save
**3. Install Handle Bars**It 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 .

= Step 5: Setting up Firestore (Cloud Database) =

== Database Configuration ==
- Go to httpsconsole.firebase.google.com/ 

- Select your project

- Select
Databasefrom 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

**After you set this location, you cannot change it later. Note: **
== CreateData ==
- 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**

= Step 6: Building up the dynamic content of the website =
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**
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

== Fetching from Firestore ==
- Open
index.jsinside the functionsfolder

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-functionsconst express = require('expressconst engines = require('consolidatevar hbs = require('handlebarsconst 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 = expressapp.engine('hbs',engines.handlebars);app.set('viewsviewsapp.set('view enginehbs
4. Authorize your application to access your Firestore DB

*Note:*
1. Change
**YOUR_SDK_NAMEjson with the file you downloaded for **credentials to access Firestore2. Change the database URL to your database URL. To see the URL you can to**Settings > Service Account**

var serviceAccount = require
YOUR_SDK_NAME.jsonadmin.initializeApp({credential: admin.credential.cert(serviceAccount), databaseURL: "httpsmyfirebaseproject-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 getFirestoreconst firestore_con = await admin.firestoreconst writeResult = firestore_con.collection('
sampledoc(' sample_docgetthen(doc => {
if (!doc.exists) { console.log('No such document }
else {return doc.data
.catch(err => { console.log('Error getting document', errreturn writeResult
}
**We use Note: ** **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.getasync (request,response) var db_result = await getFirestoreresponse.render('indexdb_resultexports.app = functions.https.onRequest(app);
7. Create
**index.hbs** inside the **views** folder. hbs is a handelbars file Note: **
8. Write this basic HTML code inside
**index.hbs** to see the fetched result


  

** {{db_result.Heading}} , db_result is the variable that was passed from the backend. Note 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
"functionapp"

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

11. Test the firebase app on your local system by running the following command. Then go to
**httplocalhost:5000** to see your basic website running

firebase serve --only hosting,functions
12. Close the server from the terminal

== Inserting to Firestore ==
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

**It will ask you to enter a document as well to create the collection to enter any sample value. Note: ** 
2. Go to
**httplocalhost: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**



Sample Form First name:

Last name:


actioninsert_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.firestorecollection(' form_dataadd({ 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 webpagedisplayed on the webpage 8. Go to httpsconsole.firebase.google.com/ then to the Database section. You should see the inserted form data = Step 7: Deploy Online (The final step) = - 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.jsremove the following code: var serviceAccount = require YOUR_SDK_NAME.jsonadmin.initializeApp({credential: admin.credential.cert(serviceAccount), databaseURL: "httpsmyfirebaseproject-bx54dasx3.firebaseio.com - Instead inside index.js, insert this into your code: admin.initializeApp(functions.configfirebase); 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 **Step 8: (Optional) Using a Custom URL** - Buy a domain from any provider like GoDaddy or any other as you feel - Go to Hostingfrom the pane on left - Click on Connect Domain 4. Enter the domain Here: 5. Follow the verification instructions *Disclaimer:* - 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.