arrow_back

Getting started with Firebase Web

Join Sign in
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

Getting started with Firebase Web

Lab 30 minutes universal_currency_alt 1 Credit show_chart Introductory
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

GSP1134

Google Cloud self-paced labs logo

Overview

In this lab you will learn the fundamentals of Firebase development for the web. If you are new to Firebase development or looking for an overview of how to get started, you are in the right place. Read on to learn about the specifics of this lab and areas that you will get hands-on practice with.

The following lab is based on the Firebase Fundamentals YouTube Series:

Getting started with Firebase Web

What you'll learn

In this lab, you will learn about the following:

  • Installing Firebase packages
  • Creating a Firebase Application
  • Importing Firebase Services
  • Browser Modules
  • Bundling with Webpack

Prerequisites

This is an introductory-level lab and the first lab you should take if you're unfamiliar with Firebase.

If you have a personal or corporate Google Cloud account or project, sign out of that account. If you stay logged in to your personal/corporate account and run the lab in the same browser, your credentials could get confused, resulting in getting logged out of the lab accidentally.

If you use ChromeOS, please run your lab using an Incognito window.

Over the course of this lab the following elements are required:

  • Understanding of Firebase
  • Understanding of Node.js
  • Creating a Firebase application suitable for the web

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To view a menu with a list of Google Cloud products and services, click the Navigation menu at the top-left. Navigation menu icon

Task 1. Installing Firebase

Before you can add Firebase to your JavaScript app, you need to create a Firebase project and register your app with that project. When you register your app with Firebase, you'll get a Firebase configuration object that you'll use to connect your app with your Firebase project resources.

Note: Before installing the Firebase packages ensure the host device has a valid Node.js installation. The lab uses Cloud Shell which already has the required packages installed.

Set up the environment ready for the Firebase application.

  1. Right click on the Cloud Shell link.
  2. Select Open link in an incognito window.
  3. Use gcloud to set the project configuration:
gcloud config set project {{{ project_0.project_id }}} Note: Cloud Shell may require authorization to complete this task.
  1. Make a new firebase-project folder and change to this directory:
mkdir firebase-project && cd $_
  1. Create a default npm project:
npm init -y
  1. Install the Firebase SDK npm package:
npm i firebase

At this point you will have a folder complete with entries for node_modules and package.json.

  1. The directory will contain the following:

Example Output

. ├── node_modules ├── package.json └── package-lock.json

The initial Firebase environment has now been successfully initialized. Next, learn how to create a Firebase application.

Task 2. Creating a Firebase Application

Create a Firebase application using the environment.

The project will use a webpack folder structure.

  1. Create a src directory within the project folder:
mkdir src
  1. Create a new file as src/index.js.
  2. Add the following content to the file src/index.js.
// import { initializeApp } from 'firebase/app'; // import { getAuth, onAuthStateChanged } from 'firebase/auth' import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js' import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js' // Add your web app's Firebase configuration const firebaseConfig = { apiKey: "{{{ project_0.startup_script.apiKey }}}", authDomain: "{{{ project_0.startup_script.authDomain }}}", projectId: "{{{ project_0.project_id }}}", storageBucket: "{{{ project_0.startup_script.storageBucket }}}", messagingSenderId: "{{{ project_0.startup_script.messageSenderId }}}", appId: "{{{ project_0.startup_script.appId }}}", measurementId: "{{{ project_0.startup_script.measurementId }}}" }; // Initialize Firebase const firebaseApp = initializeApp(firebaseConfig); Note: Additional information is available to understand how to secure a Firebase application:

The page now includes starter code for a Firebase application using JavaScript. Next add Firebase services to the existing content.

Task 3. Importing Firebase Services

Firebase JavaScript API version 9 has made a number of services available to developers. To use a service, it must be initialized prior to calling a Firebase getter function.

In Firebase v9 the use of services includes the following usage pattern:

Service Import Statement
Authentication import { getAuth } from ‘firebase/auth'
Firestore import { getFirestore } from ‘firebase/firestore'
Cloud Functions import { getFunctions } from ‘firebase/functions'
Cloud Storage import { getStorage } from ‘firebase/storage'

Import Auth

Add Authentication to the src/index.js file. To add authentication, use an import statement to tell Firebase which service is to be used. After adding the Firebase service, use the getAuth getter method on the firebaseApp.

  1. Update src/index.js to add Firebase Authentication:
const auth = getAuth(firebaseApp)
  1. The src/index.js will now look similar to below:

Example Output

// import { initializeApp } from 'firebase/app'; // import { getAuth, onAuthStateChanged } from 'firebase/auth' import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js' import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js' // Add your web app's Firebase configuration const firebaseConfig = { apiKey: "{{{ project_0.startup_script.apiKey }}}", authDomain: "{{{ project_0.startup_script.authDomain }}}", projectId: "{{{ project_0.project_id }}}", storageBucket: "{{{ project_0.startup_script.storageBucket }}}", messagingSenderId: "{{{ project_0.startup_script.messageSenderId }}}", appId: "{{{ project_0.startup_script.appId }}}", measurementId: "{{{ project_0.startup_script.measurementId }}}" }; // Initialize Firebase const firebaseApp = initializeApp(firebaseConfig); const auth = getAuth(firebaseApp) Note: In the above code example, Firebase import statement uses static packages. We will change this later in the example.

Import onAuthStateChanged

Add a new import statement for onAuthStateChanged to indicate if the current user is logged in or not. This authentication method uses the auth const variable defined in the prior stage.

  1. Add State management to the src/index.js:
// Detect auth state onAuthStateChanged(auth, user => { if (user != null) { console.log('Firebase Auth: User Logged In') } else { console.log('Firebase Auth: User Logged Out') } })
  1. The src/index.js will now look similar to below:

Example Output

// import { initializeApp } from 'firebase/app'; // import { getAuth, onAuthStateChanged } from 'firebase/auth' import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js' import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js' // Add your web app's Firebase configuration const firebaseConfig = { apiKey: "{{{ project_0.startup_script.apiKey }}}", authDomain: "{{{ project_0.startup_script.authDomain }}}", projectId: "{{{ project_0.project_id }}}", storageBucket: "{{{ project_0.startup_script.storageBucket }}}", messagingSenderId: "{{{ project_0.startup_script.messageSenderId }}}", appId: "{{{ project_0.startup_script.appId }}}", measurementId: "{{{ project_0.startup_script.measurementId }}}" }; // Initialize Firebase const firebaseApp = initializeApp(firebaseConfig); const auth = getAuth(firebaseApp) // Detect auth state onAuthStateChanged(auth, user => { if (user != null) { console.log('Firebase Auth: User Logged In') } else { console.log('Firebase Auth: User Logged Out') } }) Note: In the above example, an auth object is created by calling the getAuth getter with firebaseApp as a parameter. The auth object can then be used by the onAuthStateChanged method to validate the user status for the firebaseApp configuration.

The page now includes a reference to Firebase services. It doesn't have a HTML frontend associated with the application. Learn how to fix this in the next section on browser modules.

Task 4. Browser Modules

In the previous sections, a basic Firebase application was created. An import statement was added to use the Firebase Authentication service.

Add a simple web page to reflect the Firebase application.

  1. Create src/index.html site boilerplate and add the following contents to it:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Firebase Fundamentals</title> <script type="module" src="./index.js"></script> </head> <body> <div class="main-content"> <header> <h3>Firebase Fundamentals: Getting Started<h3> <header> </div> </body> </html>
  1. Serve the src directory in the browser on port 8080:
python3 -m http.server 8080 --directory src
  1. Use the Cloud Shell web preview option on port 8080:

Example Output

Firebase application
  1. Cancel the Cloud Shell web preview (Press CTRL-C)

With the application running successfully in the browser, the next step is to learn how to enhance the application to support webpack.

Task 5. Building with Webpack

Webpack is a common method of bundling web code and assets.

  1. Install the webpack npm packages:
npm i webpack webpack-cli --save-dev
  1. Install html-webpack-plugin package:
npm install --save-dev html-webpack-plugin
  1. Amend the package.json file to include a build script:
"scripts": { "build": "webpack" },
  1. Create a webpack.config.js file.
  2. Add the following contents to the webpack.config.js file.
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { mode : 'development', devtool: 'eval-source-map', entry: path.resolve(__dirname, 'src/index.js'), output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, plugins: [ new HtmlWebpackPlugin({ template: 'src/index.html', filename: 'index.html', inject: false }) ], }
  1. Edit src/index.js.
  2. Replace the static http links with import statements as shown below:
import { initializeApp } from 'firebase/app'; import { getAuth, onAuthStateChanged } from 'firebase/auth' // import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js' // import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js'
  1. The src/index.js will now look similar to below:

Example Output

import { initializeApp } from 'firebase/app'; import { getAuth, onAuthStateChanged } from 'firebase/auth' // import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js' // import { getAuth, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-auth.js' // Add your web app's Firebase configuration const firebaseConfig = { apiKey: "{{{ project_0.startup_script.apiKey }}}", authDomain: "{{{ project_0.startup_script.authDomain }}}", projectId: "{{{ project_0.project_id }}}", storageBucket: "{{{ project_0.startup_script.storageBucket }}}", messagingSenderId: "{{{ project_0.startup_script.messageSenderId }}}", appId: "{{{ project_0.startup_script.appId }}}", measurementId: "{{{ project_0.startup_script.measurementId }}}" }; // Initialize Firebase const firebaseApp = initializeApp(firebaseConfig); const auth = getAuth(firebaseApp) // Detect auth state onAuthStateChanged(auth, user => { if (user != null) { console.log('Firebase Auth: User Logged In') } else { console.log('Firebase Auth: User Logged Out') } })
  1. Edit the src/index.html to replace the index.js reference with main.js:
<script type="module" src="/bundle.js"></script>
  1. The src/index.html will now look similar to below:

Example Output

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Firebase Fundamentals</title> <script type="module" src="/bundle.js"></script> </head> <body> <div class="main-content"> <header> <h3>Firebase Fundamentals: Getting Started<h3> <header> </div> </body> </html>
  1. Run the build for the application from the command line:
npm run build

Example Output

> firebase-project@1.0.0 build > webpack asset bundle.js 1.53 MiB [emitted] (name: main) asset index.html 376 bytes [emitted] runtime modules 891 bytes 4 modules modules by path ./node_modules/ 571 KiB modules by path ./node_modules/@firebase/ 543 KiB modules by path ./node_modules/@firebase/auth/dist/esm2017/*.js 414 KiB ./node_modules/@firebase/auth/dist/esm2017/index.js 2.19 KiB [built] [code generated] ./node_modules/@firebase/auth/dist/esm2017/index-e3d5d3f4.js 412 KiB [built] [code generated] + 4 modules modules by path ./node_modules/firebase/ 897 bytes ./node_modules/firebase/app/dist/esm/index.esm.js 827 bytes [built] [code generated] ./node_modules/firebase/auth/dist/esm/index.esm.js 70 bytes [built] [code generated] modules by path ./node_modules/idb/build/*.js 10.8 KiB ./node_modules/idb/build/index.js 3.44 KiB [built] [code generated] ./node_modules/idb/build/wrap-idb-value.js 7.32 KiB [built] [code generated] ./node_modules/tslib/tslib.es6.mjs 15.8 KiB [built] [code generated] ./src/index.js 1020 bytes [built] [code generated] webpack 5.88.0 compiled successfully in 1031 ms
  1. Run the application from the webpack-lab/dist folder:
python3 -m http.server 8080 --directory dist
  1. Use the Cloud Shell web preview option on port 8080:

Example Output

Firebase application

At this point the backend Firebase project is being referenced. Firebase has been successfully initialized within the project.

Congratulations!

In just 30 minutes, you developed a solid understanding of Firebase on the Web and the key features. You learned:

  • How to install Firebase packages
  • Access Firebase Services
  • Creating a Webpack HTML template

You used some JavaScript with Node.js to bundle your environment source code. With the example code a Firebase template application is ready to be used within a project.

Finish your quest

This self-paced lab is part of the JavaScript Web Developer - Firebase Fundamentals quest. A quest is a series of related labs that form a learning path. Completing a quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Enroll in any quest that contains this lab and get immediate completion credit.

See the Google Cloud Skills Boost catalog for all available quests.

Take your next lab

Continue your quest with Firebase Web Developer, or check out these other Google Cloud Skills Boost labs:

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 November 20, 2023

Lab Last Tested November 20, 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.