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

Requirements

1. Google AccountIf you don’t have a Google account, you need to sign up for one. You can do this at 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 used setup_13.x because at the time of the tutorial the latest version was 13 you can check the latest version by going to https://nodejs.org/en/.

To check if Node.js and npm installed correctly, run the following commands, which will output the installed version:

node -vnpm -v

3. Firebase-CLI (Command Line Interface)These are the tools for managing, viewing, and deploying Firebase projects.

npm install -g firebase-tools

  1. Go to https: //firebase.google.com and Sign in in the upper right corner.
  2. Click Go to Console in the upper right corner .
  3. Then click 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, check to disable it).

6. Select the nearest location for Google Analytics.

7. Click Create Project and wait for it to load. You will then see something like below .

  1. Open a command line/terminal, then create and go to a new directory.

mkdir my-firebasecd-project my-firebase-project

2. To host a website on Firebase, log in to Firebase with the following command. After running the command, a browser window will open asking you to log in to firebase with your Google credentials. Enter the credentials there and Firebase will log into your system.

Firebase login

You will see something like this after successful login
  1. Now we have to initialize the project we created in the Firebase console in the system. To do this, run the following command.

firebase init

2. Press the down key and then select two thingsby pressing the space key.

  • Functions
  • Hosting

Then press Enter to continue.

3. Then select Use an existing project and then press enter.

4. Press enter on my-firebase-projector the name of the project you used.

5. Select Javascript and press enter.

6. You can say No to Do you want to use ESLint to detect probable errors and enforce the style?

See Also:  How To Create A Website Free Of Cost in 2023?

7. Type Yes to install 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 the directory name you want.
  • Type Yes for the single application page so that your dynamic URLs can be redirected to their proper destination.

9. Test the firebase application on your local system by running the following command. Then go to http://localhost:5000 to see your basic website up and running.

firebase serve -only hosting,functions

You should see something like this below after opening URL http://localhost:5000.

10. Close the server from the terminal.

  1. Here we will switch into the functions directory to do so.

cd functions

2. Install ExpressIs a minimal and flexible Node.js web application framework.

npm i express -save

3. Install Handle BarsThis is a templating engine for Node.js used for dynamic website interface.

npm i handlebars -save

4. Install consolidate

npm i consolidate -save

5. Create a folder called views inside the functions folder where we will store all the interface code.

mkdir views

6. Return to the home directory by running the following command:

cd ..

Database Configuration

  1. Go to https://console.firebase.google.com/ .
  2. Select your project.
  3. Select Database in the left panel

4. Click Create Database

5. Select Start in test mode because otherwise you will not be 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 will not be able to change it later.

Create dummy data

  1. Click start collection.

2. Enter the Collection ID, you can test for now.

3. Enter sample data. Enter sample_doc as the ID of the document. Enter Title into the Field. I like Cloud inside the Value. Then click Save.

We will divide the part into two parts, in the first part, we will see how to get the data from Firestore and use it in the website. In the second part, we will see how to submit the form data.

First, we will download the credentials to access Firestore

  1. Go to https: //console.firebase.google.com/ .
See Also:  How to create an email account with my company name

2. Click settings in the left pane and go to Project Settings.

3. Go to Service Accounts and click Generate New Private Key

4. Click Generate Key. A pop-up window will appear to download the key. Store the key inside the functions folder of your website.

Getting Firestore

  1. 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 we installed earlier.

const functions = require(‘firebase-functions’);const express = require(‘express’);const engine = require(‘consolidate’);var hbs = require ( ‘handlebar’);const admin = require(‘firebase-admin’);

3. Here we set up a few things:

  • Initialize the app using express.
  • We’ll set our engine as a handle.
  • Then we’ll tell express our front code -end will 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 database.Note: 1. Change YOUR_SDK_NAME.json with the file you downloaded to get credentials to access Firestore .2 . Change the database url to the url of your database. To see the URL, you can go 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 get data from Firestore.

  • Collection ID is sample.
  • Document ID is sample_doc.

We define the above when entering the sample data.

asynchronous 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 between the database and our website to complete.

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

8 file. Type this basic HTML inside index.hbs to see the returned result.

{{db_result.Heading}}

Note: {{db_result.Heading}} , db_result is the variable passed from the backend. .Heading is the field within the document that we define when entering the data in 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 remove this, it will always choose this file and our backend code will be useless.

See Also:  How to create a music website and earn money

11. Test the firebase application on your local system by running the following command. Next, go to http://localhost:5000 to see your basic website up and running.

Firebase Serve – Hosting Only, Features

12. Close the server from the terminal.

Pushing into Firestore

Here we will push data from our website into Firestore.

1. Create another collection called form_data, into which we will insert the form data.

Note: You will also be prompted for a document to create the collection to input any sample values ​​.

2.Navigate to http://localhost:5000 after running the following command to test on your local server.

firebase serve -only hosting,functions

3. Add the HTML code to create a sample form inside index.hbs.

{{db_result.Heading}}

<form action="/insert_data" method=”post” >

Sample form

Name:

Last name:

  • action=”/insert_data” is the path that we will define inside our function.
  • After refreshing the page, it should look like the image below.

3. Inside index.js add code that inserts data into Firestore.

asynchronous 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 written successfully!”);}). catch(function (error) { console.error(“Error writing document: “, error);});}

4. Inside index.js define the path 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 you hit submit, you should see the response as OKdisplayed on the web page.

8. Go to https://console.firebase.google.com/ and then to the Database section. You should see the data from the embedded form.

  1. We need to change a part of the code we use for authentication, because when you deploy it inline, Firebase takes care of the 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 you we’re telling Firebase to authenticate configuration information that exists when you deploy.

2. In the terminal inside your website directory, run the following command:

firebase deployment

It will take a few minutes, but after that you should see something like this:

3. Navigate to the hosting URL provided by firebase as shown in the image above.

Congratulations, you’ve finished hosting a dynamic website on Firebase.

.

Leave a Reply

Your email address will not be published. Required fields are marked *