arrow_back

Build a Serverless Web App with Firebase

Testez vos connaissances et partagez-les avec notre communauté
done
Accédez à plus de 700 ateliers pratiques, badges de compétence et cours

Build a Serverless Web App with Firebase

Atelier 1 heure universal_currency_alt 5 crédits show_chart Intermédiaire
info Cet atelier peut intégrer des outils d'IA pour vous accompagner dans votre apprentissage.
Testez vos connaissances et partagez-les avec notre communauté
done
Accédez à plus de 700 ateliers pratiques, badges de compétence et cours

GSP643

Google Cloud self-paced labs logo

Pet Theory logo

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

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:

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

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

Firebase Backend

Ruby sends Patrick an email:

Ruby

Ruby, Software Consultant

Hi Patrick,

Awesome work last week. Great to see that the clinic's data has been migrated to Firestore!

It looks like the next task is to use Firebase to host the Pet Theory website.

Ruby

Patrick

Patrick, IT Administrator

Hi Ruby,

I haven't heard of Firebase hosting before, what are the benefits? Where would I get started?

Patrick

Ruby

Ruby, Software Consultant

Hi Patrick

The primary benefit of Firebase hosting is that it is serverless, so there is no infrastructure to manage. Security rules are also embedded within the application, so permissions can be restricted to minimize issues when handling customer data.

It also has a "pay as you use" model, which means Firebase is a comprehensive mobile development platform for our use case.

Ruby

Patrick

Patrick, IT Administrator

Hi Ruby

Sounds like Firebase will make security and infrastructure management (a big part of my job) a whole lot easier. I'm excited to not be billed for idle servers either!

Patrick

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:

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

Next, help Patrick accomplish these tasks.

Task 1. Register a Firebase Application

Open an incognito window to access the Firebase Console url Firebase Console.

When requested enter the:

  • username as
  • password as .
Note:
A Firebase project labelled has been provisioned. Select this project to access Firebase products and follow this tutorial.

From the Firebase Project Overview screen, enter the following commands:

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

    Web icon highlighted

  2. When prompted for an "App nickname", type in Pet Theory.

    Pet Theory
  3. Check the box next to "Also set up Firebase Hosting for this app".

  4. Click the deploy dropdown and select Create a new site.

  5. Amend the default to include the student prefix.

    student-bucket-{{{ project_0.project_id | "PREFIX" }}}-1 Note:
    Ensure the site dropdown contains the student-bucket--1 before continuing. The site domain will be based on this setting.
  6. Click on the Register app button.

  7. Click Next > Next > Continue to console.

    Note:
    Changing the default Firebase site domain will require changes to the local environment.
    Specifically we need to:
    1. Update firebase.json to include the custom site ID. Set up deploy targets for your sites
    2. Use the site ID when using the command firebase deploy --only hosting:student-bucket--1

You have now configured the Firebase application.

Test completed task

Click Check my progress to verify the objective.

Register your Firebase app

Task 2. Enable Firebase Products

Firebase Authentication

In the Firebase Console we will setup Firebase Authentication.

  1. Click on the Build dropdown button in the left-hand navigation panel.

  2. Select Authentication tile and then click on Get Started:

  3. Click on Sign-in method tab 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.

    {{{ user_0.username | "USERNAME" }}}

    Your page should now resemble the following: Enable toggle highlighted and Project support email dropdown menu

  5. Once you have verified the above, click on the Save button.

    Note:
    When using a custom domain with Firebase, you will also need to amend the Authorized domains setting.
  6. Click the Settings tab

  7. Under the Domains heading, click the Authorized domains menu item

    Your page should now resemble the following: Authorized domains

  8. Click the Add domain button

  9. Enter the following domain:

    student-bucket-{{{ project_0.project_id | PROJECT_ID }}}-1.web.app Note:
    Adding the custom domain will allow the Firebase OAuth flow to operate correctly.
  10. Click the Add button

Test completed task

Click Check my progress to verify the objective.

Set up Firebase authentication

Firebase Firestore

In the Firebase Console we will setup Firebase Authentication.

  1. Click on the Build dropdown button in the left-hand navigation panel.

  2. Select Firestore Database tile and then click on Create database:

  3. Accept the default settings and click Next

  4. Click Create to provision Cloud Firestore

  5. Click the Rules tab

    Note:
    We want to update the security rules for the Firestore database to use authentication. In the new rules, we allow read/write on the database if the user is authenticated.
  6. Update the rules as follows:

    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; } } }

You have now set up Firebase Authentication and Firestore with a custom site identifier. The backend configuration is now complete.

Firebase Localhost

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

Patrick, IT Administrator

Hey Ruby,

Thanks for all the tips! The Firebase environment looks like it is all set up. My next task is to deploy the website developers' code.

Can you help me understand what this entails and what I need to do next?

Patrick

Ruby

Ruby, Consultant

Hi Patrick,

That's great to hear! I'll send you the instructions on how to run the application and add the following features:

  • Set up web authentication for logging in.
  • Enable customer details to be logged on the Profile page.
  • Create a self service portal for appointments.

Ruby

Patrick

Patrick, DevOps Engineer

Hi Ruby

That sounds like it will be quite a bit of work.

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

Patrick

Ruby

Ruby, Consultant

Hey Patrick

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

Firebase has some great command line tooling to help you connect your localhost to the backend Firebase project.

Use firebase init to tell Firebase which products you would like to use.

Once your project is set up you can simply call firebase deploy from the command line.

Ruby

Patrick

Patrick, IT Administrator

Hi Ruby

Wow, that's very comforting! Firebase hosting just gets better and better :-)

Patrick

Task 3. Install the Firebase CLI

Use the IDE to connect to Firebase and deploy your application.

Note:
The development environment has been preconfigured with Firebase Tools.
  1. Copy the IDE link from the Lab Details panel

    {{{ project_0.startup_script.service_url | "IDE" }}}
  2. Paste the link into a new incognito browser tab to open Cloud Code.

  3. Open a Terminal by Clicking the Application menu (Application menu icon) > Terminal > New terminal.

  4. Clone the GitHub repository from the command line:

    git clone https://github.com/rosera/pet-theory.git
  5. In the left panel, click the Explorer icon, and then Open Folder > pet-theory > lab02. Click OK.

    Note:
    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 (Application menu icon) > Terminal > New terminal.

  7. Update the node packages:

    npm i

    Example Output:

    added 630 packages, and audited 631 packages in 42s 69 packages are looking for funding run `npm fund` for details found 0 vulnerabilities npm notice npm notice New minor version of npm available! 10.7.0 -> 10.8.3 npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.8.3 npm notice To update run: npm install -g npm@10.8.3 npm notice npm warn using --force Recommended protections disabled. up to date, audited 631 packages in 2s 69 packages are looking for funding run `npm fund` for details found 0 vulnerabilities

You are now ready to link the application to the backend Firebase project.

Task 4. Authorize Firebase Access

In the IDE connect Firebase and deploy your application.

  1. Type the following command to authorize Firebase project access:

    firebase login --no-localhost Note:
    Firebase will attempt to authorize the local environment to connect with the Firebase project. Therefore ensure browser activity is performed in an incognito window to facilitate this action with the appropriate credentials.
  2. Enter in Y if asked if Firebase can collect error reporting information and press Enter.

  3. Copy and paste the URL generated into a new incognito browser tab then press Enter (directly clicking on the link results in an error).

  4. Select your lab account then click Allow.

  5. Click on Yes, I just ran this command to proceed

6 Confirm your session ID by clicking Yes, this is my session ID.

  1. You will then be given an access code:

  2. Copy the access code then paste it in the Cloud Shell prompt Enter authorization code:, and press Enter.

You should receive output similar to the following response:

Example Output:

✔ Success! Logged in as student-02-21ab4a7ce0d1@qwiklabs.net Note:
At this point the localhost is linked to the backend Firebase project.

Firebase is now connected and authorized. The next step is to initialize the Firebase products to be used.

Task 5. Initialize Firebase Products

In the IDE let Firebase know which products are required.

  1. Initialize a new Firebase project in your current working directory:

    firebase init Note:
    Running this command will step you through setting up your project directory and Firebase products. You will be asked to select the Firebase CLI features you want set up in this folder. Use the arrow keys to move up and down the list. Use the spacebar to select the product option.
  2. We need the following products:

    • Firestore
    • Hosting
  3. Use the arrow keys and the spacebar to select Firestore and Hosting. Ensure your shell matches the following and then hit Enter:

    ? 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
  4. Run through the rest of the steps to configure Firebase:

    • Key down to Use an existing project and press Enter.
    • Select your Project ID from the list then Enter.
    • Press Enter and then N to keep your firestore.rules file.
    • Press Enter and then N 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.

    Example Output:

    ✔ 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.

Task 6. Deploying to Firebase

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

  1. Edit firebase.json and update the hosting section with the site

    Expected Output

    { ... "hosting": { "site": "student-bucket-{{{ project_0.project_id | PROJECT_ID }}}-1", ... } }
  2. Deploy your firebase application, using your site ID value e.g.:

    firebase deploy --only hosting:student-bucket-{{{ project_0.project_id | PROJECT_ID }}}-1

    Output:

    ✔ Deploy complete! Project Console: https://console.firebase.google.com/project/project_0.project_id| "PROJECT_ID"/overview Hosting URL: https://student-bucket-{{{ project_0.project_id| "site" }}}-1.web.app
  3. Copy the hosting URL (should resemble .web.app) and open it in a new incognito tab.

    https://student-bucket-{{{ project_0.project_id | PROJECT_ID }}}-1.web.app Important:
    Personal credentials should not be used as authentication in this lab. Please use account: to perform the Google Sign in!
  4. 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

    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.
  5. Login with your username provided i.e. . The following page opens:

    Profile page

    A small company like Pet Theory doesn't have the resources or requisite skill set to do this. In this instance it can be beneficial to let application users log in with their existing Google account (or any other identity providers)!

    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.

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 public/customer.js file and copy and paste the following code:

    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 public/styles.css file and paste in 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-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 Terminal command line run the following command:

    firebase deploy --only hosting:student-bucket-{{{ project_0.project_id | PROJECT_ID }}}-1

    Output:

    ✔ Deploy complete! Project Console: https://console.firebase.google.com/project/project_0.project_id| "PROJECT_ID"/overview Hosting URL: https://student-bucket-{{{ project_0.project_id| "site" }}}-1.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.

    Profile form

  5. Enter some customer info—make up a name and phone number

    Customer name:

    John

    Customer phone:

    98473757454
  6. Click Save profile.

  7. Return to the Firebase Console

  8. Click Build > Firestore Database to view the profile information saved:

    Cloud Firestore, Data tabbed page

  9. 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

Pretty cool!

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

Congratulations!

Throughout the course of this lab, you created a robust serverless web application with 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 Google Sign-in to your web app and configured your database so users can add contact info and appointments. Finally, you explored and deployed code that allows users to schedule appointments and saw Firebase's real time updates in your web app. You are ready to take more labs in this learning path.

Next steps / learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated Oct 16, 2024

Lab Last Tested Oct 16, 2024

Copyright 2024 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.

Ce contenu n'est pas disponible pour le moment

Nous vous préviendrons par e-mail lorsqu'il sera disponible

Parfait !

Nous vous contacterons par e-mail s'il devient disponible