# Build a Serverless Web App with Firebase - GSP643

## **Overview**

Twelve years ago, Lily started the Pet Theory chain of veterinary clinics. The Pet Theory chain has expanded rapidly over the last few years. Their old appointment system is not able to handle the increased load or allow clients to schedule their own appointments, so Lily asked Patrick, in IT, and Ruby, a consultant, to build a cloud-based system that easily scale. In this lab you will build a fully fledged Firebase web app that allows users to log information and schedule appointments in real time.

### Architecture

This diagram gives you an overview of the services you will be using and how they connect to one another:

![Architecture diagram](https://cdn.qwiklabs.com/6pi71cGa4Nz1yhgU%2Biwp5cDD7Mv2JLuaIIHmW448Xiw%3D align="left")

## **Objectives**

In this lab, you will learn how to:

* Configure Firestore Security to automate server-side authentication and authorization.
    
* Add Google sign-in to your web app.
    
* Configure your database so users can add their contact information.
    
* Explore and deploy code that allows users to schedule appointments.
    
* Explore Firebase's real time updates in your web app.
    

### Prerequisites

This is a **intermediate level** lab. This assumes familiarity with the Cloud Console and shell environments. Experience with Firebase will be helpful, but it is not required. Before taking this lab it is recommended that you have completed the following lab:

* [Importing Data to a Firestore Database](https://google.qwiklabs.com/catalog_lab/2163)
    

You should also be comfortable editing files. You can use your favorite text editor (like `nano`, `vi`, etc.) or you can launch the code editor from Cloud Shell, which can be found in the top ribbon:

![Open Editor button](https://cdn.qwiklabs.com/I9b%2Fhu00U4e0vWPuwuG%2Fs2cYqHlz1e%2BKL%2B94gra6rzQ%3D align="left")

Once you're ready, scroll down and follow the steps below to setup your lab environment.

## **Task 1. Provisioning the Firebase environment**

Ruby sends Patrick an email:

| *Ruby, Software Consultant* | Hi Patrick, |
| --- | --- |
| *Patrick, IT Administrator* | Hi Ruby, |
| *Ruby, Software Consultant* | Hi Patrick |
| *Patrick, IT Administrator* | Hi Ruby |

Ruby sends Patrick some background information in an email, and they hold a meeting to work out the key activities. From this meeting they determine that he needs to:

* Add the Firestore CLI to the Google Cloud project.
    
* Configure a Firebase project.
    
* Establish security policies.
    

Next, help Patrick accomplish these tasks.

## **Task 2. Install the Firebase CLI**

**Note:**  
The development environment has been preconfigured with Firebase Tools.

1. Copy the **IDE** link from the Lab Details panel and paste it into a new browser tab to open Cloud Code.
    
2. Open a terminal to access the command line. In the left panel, click the **Application menu () &gt; Terminal &gt; New terminal**.
    
3. Clone the GitHub repository from the command line:
    
    ```apache
    git clone https://github.com/rosera/pet-theory.git
    ```
    
4. In the left panel, click the **Explorer** icon, and then **Open Folder &gt; pet-theory &gt; lab02**. Click **OK**.
    
5. If you get pop-up `Do you trust the authors of the files in this folder?` then check the box and click **Yes, I trust the authors**.
    
6. Open a terminal again by clicking the **Application menu () &gt; Terminal &gt; New terminal**.
    
7. Install the necessary node packages:
    
    ```apache
    npm i && npm audit fix --force
    ```
    
    Output:
    
    ```apache
    + firebase-tools@10.7.0
    added 3 packages from 11 contributors, removed 1 package and updated 8 packages in 79.808s
    ```
    

You are now ready to register a Firebase application.

## **Task 3. Register your app**

Use an incognito window to open the Firebase Console url. If required enter the username as `student-04-d9b226531981@qwiklabs.net` and password as `wUr7I5mwaI4R`.

From the Firebase console select the project labelled `qwiklabs-gcp-02-3aa62b0dc4a9`.

If you close that page, you open another incognito tab and use the following link to the [Firebase Console](https://console.firebase.google.com/?authuser=0).

1. Select the **web icon** (highlighted below) from the list of "Get started by adding Firebase to your app" icons:
    

![Web icon highlighted](https://cdn.qwiklabs.com/Y1c%2B4Z8oJdTeafmgg%2Fwwa%2Bn%2FNP%2BvjvBSeVZwtY183qs%3D align="left")

2. When prompted for an "App nickname", type in **Pet Theory**.
    
3. Then check the box next to "Also set up **Firebase hosting** for this app".
    
4. Click the dropdown featuring the PROJECT\_ID
    
5. Select the **Create a New Site** option and amend the value as follows:
    
    ```apache
    student-project-qwiklabs-gcp-02-3aa62b0dc4a9
    ```
    
6. Click on the **Register app** button.
    
7. Click **Next** &gt; **Next** &gt; **Continue to console**. You should now be on the following page:
    

![Choose a product to add to your app](https://cdn.qwiklabs.com/O6h0YyKSUHr%2FUFkBeYVCpMiGeQYvgIl65C0tPrQjHGk%3D align="left")

You have now configured Firebase for the project. Next, you will initialize the project to reference your Firebase host.

### Test completed task

Click **Check my progress** to verify the objective.

Register your app

**Check my progress**

## **Task 4. Authenticate to Firebase and Deploy**

Use the IDE to connect to Firebase and deploy your application. Type the commands in the terminal available in the editor.

1. Authenticate to Firebase:
    
    ```apache
    firebase login --no-localhost
    ```
    
2. Enter in **Y** if asked if Firebase can collect error reporting information and press **Enter**.
    
3. **Copy and paste the URL** generated in a new **incognito browser tab** and press **Enter** (directly clicking on the link results in an error).
    
4. Select your labs account and then click **Allow**. Click on **Yes, I just ran this command** to proceed, then confirm your session ID by clicking **Yes, this is my session ID**. You will then be given an access code:
    
5. Copy the access code, paste it in the Cloud Shell prompt **Enter authorization code:**, and press **Enter**. You should receive output similar to the following response:
    
    Output:
    
    ```apache
    ✔  Success! Logged in as gcpstaging86673_student@qwiklabs.net
    ```
    
6. Now initialize a new Firebase project in your current working directory:
    
    ```apache
    firebase init
    ```
    

Running this command will step you through setting up your project directory and Firebase products.

7. You will be asked to select the Firebase CLI features you want set up in this folder. Use the arrow keys and the spacebar to select **Firestore** and **Hosting**. Ensure your shell matches the following and then hit **Enter**:
    
    ```apache
    ? Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices.
     ◯ Realtime Database: Configure a security rules file for Realtime Database and (optionally) provision default insta
     ◉ Firestore: Configure security rules and indexes files for Firestore
     ◯ Functions: Configure a Cloud Functions directory and its files
    ❯◉ Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys
     ◯ Hosting: Set up GitHub Action deploys
     ◯ Storage: Configure a security rules file for Cloud Storage
    ```
    
8. Then run through the rest of the steps to configure Firebase:
    
    * Key down to **Use an existing project** and press **Enter**.
        
    * Select your Qwiklabs Project ID from the list (it's the one that starts with "qwiklabs-gcp-") then **Enter**.
        
    * Press **Enter** and then **N** to keep your firestore.rules file.
        
    * Press **Enter** and then **Y** to keep your firestore.indexes.json file.
        
    * Press **Enter** to keep your public directory and then **N** to disallow rewrites to your /index.html file.
        
    * Press **Enter** to Set up automatic builds and deploys with GitHub? and press **N**.
        
    * Enter in **N** when prompted to overwrite your 404.html file.
        
    * Enter in **N** when prompted to overwrite your index.html file.
        
    
    You should receive the following output:
    
    ```apache
    ✔  Wrote public/404.html
    ✔  Wrote public/index.html
    
    i  Writing configuration info to firebase.json...
    i  Writing project information to .firebase...
    i  Writing gitignore file to .gitignore...
    
    ✔  Firebase initialization complete!
    ```
    

The local configuration is now complete. Now the database authentication step is required to provide access between the services.

## **Task 5. Set up authentication and a database**

Return to the Firebase Console to complete this step.

1. Click on the **Project Overview** button in the left-hand navigation menu.
    
2. Select **Authentication** tile and then click on **Get Started**:
    
3. Click on **Sign-in method** and then, click on the **Google** item.
    
4. Click the **enable** toggle in the top right corner and for the **Support email for project** select your lab account from the drop down list. Your page should now resemble the following:
    
    ![Enable toggle highlighted and Project support email dropdown menu](https://cdn.qwiklabs.com/wzLcWPT%2BlNf6jxJtjkmE3OdSlCGqrjrvGoBqDXHNCTc%3D align="left")
    
5. Once you have verified the above, click on the **Save** button.
    

You have now set up Firestore authentication. In the following step you will work on hosting the application with Firebase.

### Test completed task

Click **Check my progress** to verify the objective.

Set up authentication and a database

**Check my progress**

## **Task 6. Scenario: set up the application**

You have assisted Patrick in setting up a working Firebase hosting environment where a web developer can deploy their code. However, Patrick has never enabled Firebase authentication nor has he deployed code to Firebase, so he emails Ruby for some help...

| *Patrick, IT Administrator* | Hey Ruby, |
| --- | --- |
| *Ruby, Consultant* | Hi Patrick, |
| *Patrick, DevOps Engineer* | Hi Ruby |
| *Ruby, Consultant* | Hey Patrick |
| *Patrick, IT Administrator* | Hi Ruby |

Now that Patrick has a better understanding of what is required, you will help him deploy Pet Theory as a Firebase application.

Return to the Terminal for this step. Ensure you are still in the **pet-theory/lab02** folder.

1. Run the following command to deploy your firebase application:
    
    ```apache
    firebase deploy
    ```
    
    Output:
    
    ```apache
    ✔  Deploy complete!
    
    Project Console: https://console.firebase.google.com/project/qwiklabs-gcp-7d652f8cf1f91cce/overview
    Hosting URL: https://qwiklabs-gcp-01-8be196f95006.web.app
    ```
    
2. Copy the hosting URL (should resemble `[PROJECT-ID].web.app`) and open it in a new tab.
    
3. Click on the **Sign in with Google** button:
    
    **Note:**  
    You see a **browser is not supported or 3rd party cookies and data may be disabled** error, make sure to enable cookies in your browser.
    
    ![Third-party cookies error message](https://cdn.qwiklabs.com/%2BZgcQ7aMjfJdzLYhs57qmzlLf4rt6g8geTTqZ2KsZB4%3D align="left")
    
    This can be done in Chrome by clicking the **eye** icon at the far right of the url tab and following the blue links in the popup. Click on the **site not working?** link to update your browser settings to accept cookies.
    
4. Login with your Qwiklabs account i.e. `USERNAME`. The following page opens:
    
    ![Profile page](https://cdn.qwiklabs.com/I9htDU4BTKkP6IbvXjAyr8Pa3wKb%2BDXO%2FEHK01WoaT4%3D align="left")
    
    **Note:**  
    Managing passwords is a difficult task and could expose your company to additional risk. Also, users don't want to create yet another user id and password.  
    A small company like Pet Theory doesn't have the resources or requisite skill set to do this.  
    In this instance it is much better to let the application users log in with their existing Google account (or any other identity providers)!
    

You have now deployed code to let users use Google authentication to access the appointments app.

## **Task 7. Add a customer page to your web app**

Return to the Terminal and use the editor to view the files in the **public** folder.

1. Open the `customer.js` file and copy and paste the following code:
    
    ```javascript
    let user;
    
    firebase.auth().onAuthStateChanged(function(newUser) {
      user = newUser;
      if (user) {
        const db = firebase.firestore();
        db.collection("customers").doc(user.email).onSnapshot(function(doc) {
          const cust = doc.data();
          if (cust) {
            document.getElementById('customerName').setAttribute('value', cust.name);
            document.getElementById('customerPhone').setAttribute('value', cust.phone);
          }
          document.getElementById('customerEmail').innerText = user.email;
        });
      }
    });
    
    document.getElementById('saveProfile').addEventListener('click', function(ev) {
      const db = firebase.firestore();
      var docRef = db.collection('customers').doc(user.email);
      docRef.set({
        name: document.getElementById('customerName').value,
        email: user.email,
        phone: document.getElementById('customerPhone').value,
      })
    })
    ```
    
2. Open the `styles.css` file and paste in the following code:
    
    ```css
    body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
    #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px 16px; border-radius: 3px; }
    #message h3 { color: #888; font-weight: normal; font-size: 16px; margin: 16px 0 12px; }
    #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
    #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
    #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
    #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
    #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
    #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
    @media (max-width: 600px) {
      body, #message { margin-top: 0; background: white; box-shadow: none; }
      body { border-top: 16px solid #ffa100; }
    }
    ```
    
3. From the command line run the following command:
    
    ```apache
    firebase deploy
    ```
    
    Output:
    
    ```apache
    ✔  Deploy complete!
    
    Project Console: https://console.firebase.google.com/project/qwiklabs-gcp-7d652f8cf1f91cce/overview
    Hosting URL: https://qwiklabs-gcp-01-8be196f95006.web.app
    ```
    
4. Go to your application tab and **hard refresh the page with CMND+SHIFT+R (Mac) or CTRL+SHIFT+R (Windows). Simple refreshing will not display the needed updates.** Enter some customer info—make up a name and phone number and click **Save profile**.
    
    ![Profile form](https://cdn.qwiklabs.com/fsaaHsEVOe56MJoJwrgGZsbNqEe8XL%2BTdDE6edndMKY%3D align="left")
    
5. Return to the [Firebase Console](https://console.firebase.google.com/) and click **Build &gt; Firestore Database** to view the profile information saved:
    
    ![Cloud Firestore, Data tabbed page](https://cdn.qwiklabs.com/f%2BeipVEYxggTgLahbEvRo3S93%2BuknMqguIjtSEQS3ug%3D align="left")
    
6. Return to the web app page and click on the **Appointments** link. You will see a blank page since it has not deployed the appointments code yet.
    

### Test completed task

Click **Check my progress** to verify the objective.

Add a customer page to your web app

**Check my progress**

Pretty cool! Firestore updates clients (web apps and native mobile apps) in real time, without the user having to refresh or reload.

---

## Solution of Lab

### New Solution

%[https://youtu.be/uBdt7EWAlwI] 

* Go to `Firebase Console` from [here](https://console.firebase.google.com/)
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1757775780794/ca6a8cd8-d994-4a76-adf2-43523c513b7b.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1757775786833/02edbbf9-4a58-4491-97e4-dba60359d124.png align="center")

* Register your app name :
    

```apache
Pet Theory
```

* FOLLOW THE VIDEO FOR CREATING THE DATABASE
    
* RUN COMMANDS IN NEW TERMINAL
    

```apache
curl -LO raw.githubusercontent.com/ePlus-DEV/storage/refs/heads/main/labs/GSP643/lab.sh
source lab.sh
```

**Script Alternative**

```apache
curl -LO raw.githubusercontent.com/Titash-shil/Build-a-Serverless-Web-App-with-Firebase-GSP643-Updated-/refs/heads/main/qwiklab_explorers_gsp643.sh
sed -i 's/\r$//' qwiklab_explorers_gsp643.sh
source qwiklab_explorers_gsp643.sh
```

* FOLLOW VIDEO FOR NEXT STEPS
    

---

![]( align="center")

#### Copy Customer name & Paste:

```apache
John
```

#### Copy Customer phone No & Paste:

```apache
98473757454
```

---

### Old Solution

%[https://www.youtube.com/watch?v=lGi5pyyUsew] 

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119496852/715447dd-aeeb-4abd-ba5d-c19ff622a0d7.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119509153/adcb2d4d-6300-4a0b-a84a-c4e4d8711803.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119515017/523474b2-7bd6-4587-aabc-3790c195c7f3.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119523049/059911ab-1fce-49b4-8273-79ce02908ab8.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119528596/df532d32-a94d-4d0a-8dbd-f6aa0bd6e3e5.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119551409/f2cef415-05e1-40f0-86f5-87e78b8658c0.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119557820/e90dcdba-f15c-482d-9fba-9372f184bb23.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119561922/df9cdb91-e8d5-4ac4-9d69-adecdb6a0a5f.png align="center")

```apache
curl -LO raw.githubusercontent.com/quiccklabs/Labs_solutions/master/Build%20a%20Serverless%20Web%20App%20with%20Firebase/quicklabgsp643.sh
source quicklabgsp643.sh
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119920311/0d7f60db-2800-431e-83d1-760539752428.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119931325/e54ed947-e480-4365-8305-fded824030fb.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119949837/b408ac7e-1d3c-45fb-9224-c950106992e5.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724119964811/b076610f-772f-46e4-a37e-9e79bde12e85.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724120097283/fcf324aa-c863-41b2-ba58-76f9144e9c17.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724120118095/7838edac-b9e7-4e50-a96a-fba3b071e281.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724120132139/3f20f94a-352c-49ac-8a67-c387a673df18.png align="center")
