Build a serverless web app with Firebase | Google Cloud Skills Boost (2023)

GSP643

Build a serverless web app with Firebase | Google Cloud Skills Boost (1)

Build a serverless web app with Firebase | Google Cloud Skills Boost (2)

Review

For laboratories inRadionica Google Cloud Run Serverless, you'll read a fictional business scenario and help the characters with their serverless migration plan.

12 years ago Lily started the Pet Theory chain of veterinary clinics. The Pet Theory chain has expanded rapidly over the past few years. Their old scheduling system couldn't handle the increased workload or allow clients to schedule appointments themselves, so Lily asked Patrick from IT and Ruby, a consultant, to build a cloud-based system that could easily scale.

In the previous lab, Migrating Data to a Firestore Database, you learned how to useFirestorefor hosting customer data. In this lab, you'll build a full-featured Firebase web application that allows users to capture information and schedule meetings in real-time.

Architecture

This diagram gives you an overview of the services you will use and how they connect to each other:

Build a serverless web app with Firebase | Google Cloud Skills Boost (3)

What do you want to learn

In this lab you will learn how to:

  • Enable the Firebase API in your Google Cloud project.
  • Create and configure a Firebase project.
  • Configure Firestore Security to automate server-side authentication and authorization.
  • Add Google login to your web app.
  • Configure your database to allow users to add their contact information.
  • Research and implement code that allows users to schedule meetings.
  • Explore Firebase's real-time updates in your web app.

Prerequisites

This isbasic levellaboratory. This requires familiarity with Cloud Console and the shell environment. Experience with Firebase would be helpful but not required. Before taking this lab, it is recommended that you complete the following Qwiklab:

You should also be comfortable editing files. You can use your favorite text editor (such asnano,vietc.), or you can launch the code editor from Cloud Shell, located on the top ribbon:

Build a serverless web app with Firebase | Google Cloud Skills Boost (4)

When you're ready, scroll down and follow the steps below to set up your lab environment.

Task 1. Preparing the Firebase environment

Ruby sends Patrick an email:

Build a serverless web app with Firebase | Google Cloud Skills Boost (5)

Ruby, a software consultant

Book Patrick,

Great job last week. Great to see the clinic data migrated to Firestore!

The next task seems to be using Firebase to host the Pet Theory website.

To rub

Build a serverless web app with Firebase | Google Cloud Skills Boost (6)

Patrik, IT-administrator

Hi Ruby,

I haven't heard of Firebase hosting before, what are the benefits? Where do I start?

Patrik

Build a serverless web app with Firebase | Google Cloud Skills Boost (7)

Ruby, a software consultant

Book Patrick

The primary advantage of Firebase hosting is that it is serverless, so there is no infrastructure to manage. Security rules are also built into the application so that permissions can be restricted to reduce problems when handling user data.

It also has a pay-as-you-go model, which means Firebase is the all-in-one mobile development platform for our use case.

To rub

Build a serverless web app with Firebase | Google Cloud Skills Boost (8)

Patrik, IT-administrator

Hi Ruby

It looks like Firebase will make managing security and infrastructure (a big part of my job) a lot easier. I'm happy they don't even charge me for idle servers!

Patrik

Ruby sends Patrick some background information in an email and they have a meeting to arrange the main activities. From this meeting, they decide that he will:

  • Add the Firestore CLI to the Google Cloud project.
  • Create a Firestore database.
  • Set up a Firebase project.
  • Establish security policies.

Then help Patrick complete these tasks.

Task 2. Install the Firebase CLI

Note:The development environment is preconfigured with Firebase tools.
  1. CopyIDElink 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. Click on in the left panelapplication menu (Build a serverless web app with Firebase | Google Cloud Skills Boost (9)) > Terminal > Novi terminal.

  3. Clone the GitHub repository from the command line:

git-clone https://github.com/rosera/pet-theory.git
  1. Click on in the left panelResearchericon, and thenOpen folder > pet-theory > lab02. ClickAlright.

  2. Open terminal

  3. Install the required node packages:

npm and && npm revision fix --force

Production:

+ firebase-tools@10.7.0 added 3 packages from 11 contributors, removed 1 package, and updated 8 packages in 79,808 s

You are now ready to create a Firestore database.

Task 3. Set up the Firestore database

Prepare the terminal environment to use the Firestore database.

  1. Set the project area to:
gcloud config set compute/region {{{project_0.default_region|REGION}}}
  1. ActivateApp Engineapplications:

    gcloud app create --region={{{project_0.default_region|REGION}}}
  2. Create a Firestore database:

    gcloud firestore database create --region={{{project_0.default_region|REGION}}}

You are now ready to create a Firestore project and connect it to your Google Cloud account.

Task 4. Create a Firebase project

openFirebase consoleand et incognitovindue.

Note:The lab includes Firebase permissions. Copy the Firebase Console link to access Firebase. UseUsername Passwordcomes with a Firebase Authentication Lab.
  1. Click on the account icon in the upper right corner of the page and verify that it is the Qwiklabs student account you set up for this lab.

  2. Then clickAdd a project. When prompted for a project name, use the project ID from the drop-down menu.

  3. Accept the Firebase terms and conditions and clickContinue. Potvrdite plan naplate "Pay As You Go".

  4. ClickContinueand on the next pagedeactivateGoogle Analytics for your Firebase project.

  5. Then clickAdd Firebase. ClickContinuewhen you see a notification that your new project is ready:

Build a serverless web app with Firebase | Google Cloud Skills Boost (10)

Test the completed task

ClickCheck my progressto check the target.

Create a Firebase project

Task 5. Register your application

After completing the last step, you should be in the Firebase console. If you close this page, you will open another anonymous tab and use the following link toFirebase console.

  1. chooseweb-icon(highlighted below) from the "Start adding Firebase to your app" icon list:

Build a serverless web app with Firebase | Google Cloud Skills Boost (11)

  1. When prompted for "Application Nickname", enter itPet theory.

  2. Then check the box next to "Also configureFirebase-hostingthis application".

  3. click onRegister the applicationbutton.

  4. ClickFollowing>Following>Keep comforting. You should now be on the following page:

Build a serverless web app with Firebase | Google Cloud Skills Boost (12)

You have now configured Firebase for the project. You will then initialize the project to reference your Firebase host.

Test the completed task

ClickCheck my progressto check the target.

Register your application

Task 6. Authenticate to Firebase and deploy

Use the IDE to connect to Firebase and deploy your app. Enter the commands in the available terminal in the editor.

  1. Firebase authentication:
login to firebase --no-localhost
  1. A nurseYif asked if Firebase can collect error reporting information, tapA nurse.

  2. Copy and paste the URLgenerated in the newincognitobrowserfaneand pressureA nurse(directly clicking on the link leads to an error).

  3. Select your Labs account, then clickAllow. click onYes, I just ran this commandto continue, then confirm your session ID by clickingYes, this is my session ID. You will then receive a password:

  4. Copy the password, paste it into the Cloud Shell promptEnter password:, and pressA nurse. You should get output similar to the following response:

Production:

✔ Success! Submitted as gcpstaging86673_student@qwiklabs.net
  1. Now initialize a new Firebase project in your current working directory:
firebase init

Running this command will walk you through the workbook and Firebase product setup.

  1. You will be prompted to select the Firebase CLI features you want to configure in this folder. Use arrow keys and spacebar to selectFirestoreiServer Services. Make sure your shell matches the following, then tapA nurse:
? What Firebase CLI functions do you want to configure for this directory? Press the space bar to select functions, then press Enter to confirm the selection. ◯ Realtime Database: Configure security rules file for Realtime Database and (optionally) provide default insta ◉ Firestore: Configure security rules and index files for Firestore ◯ Functions: Configure Cloud Functions folder and its files❯◉ Hosting: Configure files for Firebase Hosting and (optional) configure GitHub Action deployment ◯ Hosting: Configure GitHub Action deployment ◯ Storage: Configure security rules file for Cloud Storage
  1. Then run the rest of the steps to configure Firebase:
  • Download onUse an existing projectand pressureA nurse.
  • Select your Qwiklabs project ID from the list (it's the one that starts with "qwiklabs-gcp-") and thenA nurse.
  • PressA nurseand thenNto save your firestore.rules file.
  • PressA nurseand thenYto keep your firestore.indexes.json file.
  • PressA nurseto keep your public folder and thenNto disable overwriting your /index.html file.
  • PressA nurseset up automatic build and deployment with GitHub? and pressureN.
  • A nurseNwhen prompted to overwrite your 404.html file.
  • A nurseNwhen prompted to overwrite your index.html file.

You should get the following output:

✔ Writing public/404.html✔ Writing public/index.htmli Writing configuration information to firebase.json...i Writing project information to .firebase...i Writing gitignore file to .gitignore...✔ Firebase initialization complete !

The local configuration is now complete. A database authentication step is now required to allow access between services.

Task 7. Set up authentication and database

Return to the Firebase console to complete this step.

  1. click onProject overviewbutton in the left navigation menu.

  2. chooseApprovaltile, then clickGet started:

  3. Click on the list of login service providersGooglearticle.

  4. click onactivateswitch in the upper right corner and forProject support emailselect your lab account from the drop-down list. Your page should now look like this:

Build a serverless web app with Firebase | Google Cloud Skills Boost (13)

  1. After confirming the above, click onSavingbutton.

You have now configured Firestore authentication. In the next step, you'll work on hosting the app with Firebase.

Test the completed task

ClickCheck my progressto check the target.

Set up authentication and database

Task 8. Scenario: set up the application

You helped Patrick set up a working Firebase hosting environment where a web developer can deploy their code. However, Patrick never enabled Firebase authentication, nor did he deploy the code to Firebase, so he emails Ruby for help…

Build a serverless web app with Firebase | Google Cloud Skills Boost (14)

Patrik, IT-administrator

Hi Ruby,

Thanks for all the advice! The Firebase environment looks like everything is set up. My next task is to implement the code for the site developers.

Can you help me understand what this means and what I need to do now?

Patrik

Build a serverless web app with Firebase | Google Cloud Skills Boost (15)

Ruby, the counselor

Book Patrick,

That's nice to hear! I am sending you instructions on how to run the program and add the following features:

  • Configure web authentication for login.
  • Enable customer information login on profile page.
  • Create a self-service portal for scheduling appointments.

To rub

Build a serverless web app with Firebase | Google Cloud Skills Boost (16)

Patrick, DevOps Engineer

Hi Ruby

It looks like it's going to be a lot of work.

Does this mean that I will have to make structural changes every time I want to add something new? Not to mention the time it will take to see these updates...

Patrik

Build a serverless web app with Firebase | Google Cloud Skills Boost (17)

Ruby, the counselor

Book Patrick

You can do most of the heavy lifting with the Firebase libraries.

Viewing updates in your browser is as easy as callingfirebase implementationfrom the command line.

Make changes, deploy and preview your changes on the site!

To rub

Build a serverless web app with Firebase | Google Cloud Skills Boost (18)

Patrik, IT-administrator

Hi Ruby

Wow, that is very comforting! Firebase hosting keeps getting better and better :-)

Patrik

Now that Patrick has a better understanding of what's needed, you'll help him implement Pet Theory as a Firebase app.

Task 9 Configure Firestore authentication and add login to your web application

For this step, return to the terminal. You should still have a command line session open from the previous Firebase initialization.

  1. Run the following command to list the folders and files in yourlab02directory:
ls -1
  1. Make sure your output looks like this:
README.mdfirebase.jsonfirestore.indexes.jsonfirestore.rulesnode_modulespackage-lock.jsonpackage.jsonpublicsolution
  1. Use the code editor to open itpet-theory/lab02/firestore.rules:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /customers/{email} { allow read write: if request.auth.token.email == email; } match /customers/{email}/{document=**} { allow read, write: if request.auth.token.email == email; } }}Note:The configuration ensures that the Firestore database user can only access their own data. The firestore.rules file is used to provide security to the Firestore database. Learn more aboutFirestore database security.

Task 10. Implement your application

With all the changes you have made, you are ready to deploy the application. Make sure you are still in thepet theory/lab02map.

  1. Run the following command to deploy your firebase app:
firebase implementation

Production:

✔ Implementation complete! Project Console: https://console.firebase.google.com/project/qwiklabs-gcp-7d652f8cf1f91cce/overviewHosting URL: https://qwiklabs-gcp-01-8be196f95006.web.app
  1. Copy the hosting URL (it should look like[PROJEKT-ID].web.app) and open it in a new tab.
  2. click onSign in with Googlebutton:
Note:You see onebrowser is not supported or third-party cookies and data may be disablederrors, make sure you have cookies enabled in your browser.Build a serverless web app with Firebase | Google Cloud Skills Boost (19)This can be done in Chrome by clicking oneyeicon on the far right of the url tab and follow the blue links in the popup window. click onpage not working?link to update your browser settings to accept cookies.
  1. Select your Google account. The following page opens:

Build a serverless web app with Firebase | Google Cloud Skills Boost (20)

Note:Password management is a difficult task and can expose your business to additional risks. Also, users don't want to create another user ID and password. A small company like Pet Theory doesn't have the resources or skills to do that. In this case, it's much better to let app users sign in with their existing Google account (or other identity providers)!

You have now implemented code that allows users to use Google authentication to access the appointment scheduling application.

Task 11. Add a user page to your web application

Go back to the terminal and use an editor to view the filespublicmap.

  1. opencould.jsfile and copy and paste the following code:
lad bruger;firebase.auth().onAuthStateChanged(function(newUser) { user = newUser; if (bruger) { const db = firebase.firestore(); db.collection("kunder").doc(bruger.e-mail ). 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('klik' , funkcija (ev) { const db = firebase.firestore(); var docRef = db.collection('customers').doc(user.email); docRef.set({ name: document.getElementById('customerName'). vrijednost, e-pošta: user.email, telefon: document.getElementById('customerPhone').value, })})
  1. openstyles.cssfile and paste the following code:
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 alignment: center; background: #039be5; text-transformation : capital letters ; 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 alignment: center; font size: 13px; }@media (max-width: 600px) { body, #message { margin-top: 0; background: white; box-shadow: none; } body { border-top: 16px solid #ffa100; }}
  1. Run the following command from the command line:
firebase implementation

Production:

✔ Implementation complete! Project Console: https://console.firebase.google.com/project/qwiklabs-gcp-7d652f8cf1f91cce/overviewHosting URL: https://qwiklabs-gcp-01-8be196f95006.web.app
  1. Go to the application tab andforce refresh the page using CMND+SHIFT+R (Mac) or CTRL+SHIFT+R (Windows). Simple Update does not show the required updates.Enter some customer information - create a name and phone number and clickSave profile.

Build a serverless web app with Firebase | Google Cloud Skills Boost (21)

  1. Return toFirebase consoleand clickBuild > Firestore Databaseto view saved profile data:

Build a serverless web app with Firebase | Google Cloud Skills Boost (22)

  1. Go back to the web application page and clickAppointmentsconnection. You will see a blank page because the offer code has not been implemented yet.

Test the completed task

ClickCheck my progressto check the target.

Add a user page to your web application

Task 12. Allow users to schedule appointments

Create a page that allows users to schedule meetings.

  1. Return to the Code Editor tab. You will add the code in two filespublicdirectory.

  2. In the side menu, selectagreements.htmland insert the following code:

Pet Theory ponude

Zakazani terms


Make a new appointment



  1. Open nowagreements.jsfile and paste the following code:
let user;firebase.auth().onAuthStateChanged(function(newUser) { user = newUser; if (user) { const db = firebase.firestore(); const appColl = db.collection('customers').doc(user. email).collection('agreements'); appColl.orderBy('time').onSnapshot(function(snapshot) { const div = document.getElementById('agreements'); div.innerHTML = ''; snapshot.docs.forEach (agreement => { div.innerHTML += formatDate(agreement.data().time) + '
'; }) if (div.innerHTML == '') { div.innerHTML = 'Nemate plana učitavanja' ; } }); }});const timeslots = document.getElementById('timeslots');getOpenTimes().forEach(time => { timeslots.add(nova opcija(formatDate(time), time));}); document.getElementById('makeAppointment').addEventListener('click', function(ev) { const millis = parseInt(timeslots.selectedOptions[0].value); if (millis > 0) { const db = firebase.firestore() db.collection('kunder').doc(bruger.e-mail).collection('aftaler').add({ time: millis }) timeslots.remove(timeslots.selectedIndex); }})funktion getOpenTimes() { const retVal = []; lad startdato = ny dato(); datum početka.setMinutes(0); početni datum.postavi sekunde(0); startDate.setMilliseconds(0); lad millis = startDate.getTime(); while (retVal.length < 5) { const timer = Math.floor(Math.random() * 5) + 1; mililisi += mjerač vremena * 3600 * 1000; if (isDuringOfficeHours(milis)) { retVal.push(milis); } } returner retVal;}funktion isDuringOfficeHours(milis) { const aDatum = novi datum(milis); return aDate.getDay() != 0 && aDate.getDay() != 6 && aDate.getHours() >= 9 && aDate.getHours() <= 17;}funktionsformatDate(milis) { const aDate = new Date(milis ); const days = ['søn', 'man', 'tir', 'on', 'tors', 'fre', 'lør']; const months = ['jan', 'feb', 'ožu', 'travanj', 'svibanj', 'lip', 'srp', 'kolovoz', 'rujan', 'okt', 'stu', 'pro . ']; returdage[aDate.getDay()] + ' ' + aDate.getDate() + ' ' + mjeseci[aDate.getMonth()] + ', ' + aDate.getHours() + ':' + (aDate.getMinutes( ) < 10? '0'+aDate.getMinutes(): aDate.getMinutes());}
  1. Now that your files are built, you can see your changes. Run the following command in Cloud Shell to deploy your application:
firebase implementation

Production:

✔ Implementation complete! Project Console: https://console.firebase.google.com/project/qwiklabs-gcp-7d652f8cf1f91cce/overviewHosting URL: https://qwiklabs-gcp-01-8be196f95006.web.app
  1. Refresh the web application tab where you previously had a blank page. Go ahead and make a few appointments:

Build a serverless web app with Firebase | Google Cloud Skills Boost (23)

  1. Now go to Firebase console, clickBuild > Firestore Databaseand chooseagreementsthe collection you just created under your user.

  2. You should see a similar collection of offer codes:

Build a serverless web app with Firebase | Google Cloud Skills Boost (24)

Task 13. See Firestore updates in real time

Firestore is a real-time database. Add real-time updates to your app to take advantage of this.

  1. Open a new browser tab and tap on it[ID PROJEKTA].web.app, then sign in with the Google button and clickAppointments.

  2. Arrange two browser tabs next to each other. Schedule a new appointment in the first browser window.

  3. Now look at the second browser tab - you should see the offer automatically added without needing to refresh:

Build a serverless web app with Firebase | Google Cloud Skills Boost (25)

That's great! Firestore updates clients (web apps and native mobile apps) in real-time without requiring the user to refresh or reload.

  1. Go to the Firebase console, click onDatatab in Cloud Firestore and edit the data. You can even deleteagreementscollection during user registration. Both browser windows are constantly updated in real time.

Congratulations!

During this lab, you built a robust serverless web application using Firebase. After creating and configuring a Firebase project, you added Firestore security to automate server-side authentication and authorization. You then went ahead and added a Google login to your web application and set up your database to allow users to add contact and appointment information. Finally, you've researched and implemented code that allows users to schedule meetings and view real-time Firebase updates in your web application. You are ready for additional laboratory exercises in this learning path.

Complete your mission

This self-paced pace lab is part ofRadionica Google Cloud Run ServerlessiBuild apps and websites with Firebasesearches. The quest is a series of connected labs that make up the learning path. Completing the task earns you a badge that recognizes your achievement. You can post your badge or badges publicly and link to them on your online resume or social media account. Sign up for any assignment that contains this lab exercise and receive instant credit for completion. Refers toGoogle Cloud Skills Boost katalogfor all available tasks.

Take your next lab

Continue your quest with the next lab in the series,Build a serverless application with Cloud Run that creates PDF filesorDeploy a Hugo site with Cloud Build and Firebase Pipeline.

Next step / Learn more

Google Cloud -What is serverless?

Google Cloud training and certification

...helps you make the most of Google Cloud technologies.Our classesincorporate technical skills and best practices to quickly get up to speed and continue your learning journey. We offer basic to advanced training levels with on-demand, live and virtual options to fit your busy schedule.Certificateshelp you validate and prove your skills and expertise in Google Cloud technologies.

Handbook Last updated on August 10, 2023

The laboratory was last tested on August 10, 2023

Copyright 2023 Google LLC. All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

References

Top Articles
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated: 01/11/2023

Views: 6106

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.