arrow_back

Getting Started with Firebase Email Authentication

Sign in Join
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 Email Authentication

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

GSP1135

Google Cloud self-paced labs logo

Overview

In this lab you will learn the fundamentals of Firebase Email/Password Authentication 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 Authentication on the web

In this lab learn how to create a basic web application using webpack.

  • Installing Firebase
  • Creating a Firebase Application
  • Email/Password authentication
  • Creating a Password based account

Prerequisites

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

  • Understanding of Webpack
  • Understanding of Node.js

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. Configuring the Firebase Environment

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.

Open the Firebase console in a new Incognito tab. Follow the instructions to setup email authentication for the Firebase project:

  1. Select the project from the Firebase console:
Note:

If presented with Firebase Terms and Conditions, confirm these settings before proceeding.

  1. Click the Authentication option on the main screen.
  2. Click the Get started button.
  3. Select Email/Password from Native providers option.
  4. Click Enable to allow users to sign in with an Email/Password combination.
  5. Click the Save button.
Note:

At this point the Firebase project includes a Sign-in provider configured for Authentication. To access this information open the Firebase project and view the Authentication Sign-in method. Ensure the status is set as enabled.

By default there are no users configured for the sign-in provider.

In the Firebase project, a web application has been created. Later in the lab this configuration will be used to link the web application to the Firebase project.

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

Task 2. Creating a Firebase Web Application

The following section creates the elements required to perform Firebase Authentication using an email/password combination on the web.

Firebase Authentication information can be accessed via the Firebase site.

Service Import Statement Description
Authentication import { getAuth } from ‘firebase/auth' Returns the Auth instance associated with the provided FirebaseApp. If no instance exists, initializes an Auth instance with platform-specific default dependencies.
Authentication import { onAuthStateChanged } from ‘firebase/auth' Adds an observer for changes to the user's sign-in state.
Authentication import { signOut } from ‘firebase/auth' Signs out the current user.
Authentication import { createUserWithEmailAndPassword } from ‘firebase/auth' Creates a new user account associated with the specified email address and password.
Authentication import { signInWithEmailAndPassword } from ‘firebase/auth' Asynchronously signs in using an email and password.
Authentication import { connectAuthEmulator } from ‘firebase/auth' Changes the Auth instance to communicate with the Firebase Auth Emulator, instead of production Firebase Auth services.
Note:

Before installing the Firebase packages ensure the host device has a valid Node.js installation.

Follow the instructions below to create a Node.js 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 | "PROJECT_ID" }}}
  1. In the Cloud Shell terminal create a firebase-project folder:
mkdir firebase-project && cd $_
  1. Create a default npm project:
npm init -y
  1. Install the Firebase SDK package:
npm i firebase

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

In addition the firebase configuration files:

File Description
firebase.json Provides the configuration for the available Firebase components. In our example, auth and ui elements will be contained within this file together with port information.
.firebaserc Provides the linked project configuration information.

With the Firebase environment setup, the application code can be created to use the installed Firebase packages.

Return to the Cloud Shell terminal.

  1. Make a src folder within the firebase-project:
mkdir ~/firebase-project/src
  1. Create a src/index.js file with the following content:
import './styles.css'; import { hideLoginError, showLoginState, showLoginForm, showApp, showLoginError, btnLogin, btnSignup, btnLogout } from './ui' import { initializeApp } from 'firebase/app'; import { getAuth, onAuthStateChanged, signOut, createUserWithEmailAndPassword, signInWithEmailAndPassword, connectAuthEmulator } from 'firebase/auth'; // 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); // Login using email/password const loginEmailPassword = async () => { const loginEmail = txtEmail.value const loginPassword = txtPassword.value // step 1: try doing this w/o error handling, and then add try/catch await signInWithEmailAndPassword(auth, loginEmail, loginPassword) // step 2: add error handling // try { // await signInWithEmailAndPassword(auth, loginEmail, loginPassword) // } // catch(error) { // console.log(`There was an error: ${error}`) // showLoginError(error) // } } // Create new account using email/password const createAccount = async () => { const email = txtEmail.value const password = txtPassword.value try { await createUserWithEmailAndPassword(auth, email, password) } catch(error) { console.log(`There was an error: ${error}`) showLoginError(error) } } // Monitor auth state const monitorAuthState = async () => { onAuthStateChanged(auth, user => { if (user) { console.log(user) showApp() showLoginState(user) hideLoginError() hideLinkError() } else { showLoginForm() lblAuthState.innerHTML = `You're not logged in.` } }) } // Log out const logout = async () => { await signOut(auth); } btnLogin.addEventListener("click", loginEmailPassword) btnSignup.addEventListener("click", createAccount) btnLogout.addEventListener("click", logout) const auth = getAuth(firebaseApp); // connectAuthEmulator(auth, "http://localhost:9099"); monitorAuthState(); Note:

The firebaseConfig object definition has been replaced with the configuration from the Firebase project.

An updated configuration is required to enable the application to communicate with the designated Firebase project.

  1. Create a src/ui.js file with the following content:
import { AuthErrorCodes } from 'firebase/auth'; export const txtEmail = document.querySelector('#txtEmail') export const txtPassword = document.querySelector('#txtPassword') export const btnLogin = document.querySelector('#btnLogin') export const btnSignup = document.querySelector('#btnSignup') export const btnLogout = document.querySelector('#btnLogout') export const divAuthState = document.querySelector('#divAuthState') export const lblAuthState = document.querySelector('#lblAuthState') export const divLoginError = document.querySelector('#divLoginError') export const lblLoginErrorMessage = document.querySelector('#lblLoginErrorMessage') export const showLoginForm = () => { login.style.display = 'block' app.style.display = 'none' } export const showApp = () => { login.style.display = 'none' app.style.display = 'block' } export const hideLoginError = () => { divLoginError.style.display = 'none' lblLoginErrorMessage.innerHTML = '' } export const showLoginError = (error) => { divLoginError.style.display = 'block' if (error.code == AuthErrorCodes.INVALID_PASSWORD) { lblLoginErrorMessage.innerHTML = `Wrong password. Try again.` } else { lblLoginErrorMessage.innerHTML = `Error: ${error.message}` } } export const showLoginState = (user) => { lblAuthState.innerHTML = `You're logged in as ${user.displayName} (uid: ${user.uid}, email: ${user.email}) ` } hideLoginError()
  1. Create a src/styles.css with the following content:
* { box-sizing:border-box; } body { font-family: Helvetica; background: #eee; -webkit-font-smoothing: antialiased; } .header { text-align:center; margin-top: 4em; } h1, h3 { font-weight: 300; } h1 { color: #636363; } h3 { color: #4a89dc; } form { width: 380px; margin: 4em auto; padding: 3em 2em 2em 2em; background: #fafafa; border: 1px solid #ebebeb; box-shadow: rgba(0,0,0,0.14902) 0px 1px 1px 0px,rgba(0,0,0,0.09804) 0px 1px 2px 0px; } .group { position: relative; margin-bottom: 45px; } input { font-size: 18px; padding: 10px 10px 10px 5px; -webkit-appearance: none; display: block; background: #fafafa; color: #636363; width: 100%; border: none; border-radius: 0; border-bottom: 1px solid #757575; } input:focus { outline: none; } /* Label */ label { color: #999; font-size: 18px; font-weight: normal; position: absolute; pointer-events: none; left: 5px; top: 10px; transition: all 0.2s ease; } /* Error Label */ .errorlabel { font-size: 18px; padding: 10px 10px 10px 5px; -webkit-appearance: none; display: block; background: #fafafa; color: #ff0000; width: 100%; border: none; border-radius: 0; border-bottom: 1px solid #ff0000; } /* active */ input:focus ~ label, input.used ~ label { top: -20px; transform: scale(.75); left: -2px; /* font-size: 14px; */ color: #4a89dc; } /* Underline */ .bar { position: relative; display: block; width: 100%; } .bar:before, .bar:after { content: ''; height: 2px; width: 0; bottom: 1px; position: absolute; background: #4a89dc; transition: all 0.2s ease; } .bar:before { left: 50%; } .bar:after { right: 50%; } /* active */ input:focus ~ .bar:before, input:focus ~ .bar:after { width: 50%; } /* Highlight */ .highlight { position: absolute; height: 60%; width: 100px; top: 25%; left: 0; pointer-events: none; opacity: 0.5; } /* active */ input:focus ~ .highlight { animation: inputHighlighter 0.3s ease; } /* Animations */ @keyframes inputHighlighter { from { background: #4a89dc; } to { width: 0; background: transparent; } } /* Button */ .button { position: relative; display: inline-block; padding: 12px 24px; margin: .3em 0 1em 0; width: 100%; vertical-align: middle; color: #fff; font-size: 16px; line-height: 20px; -webkit-font-smoothing: antialiased; text-align: center; letter-spacing: 1px; background: transparent; border: 0; border-bottom: 2px solid #3160B6; cursor: pointer; transition: all 0.15s ease; } .button:focus { outline: 0; } /* Button modifiers */ .buttonBlue { background: #4a89dc; text-shadow: 1px 1px 0 rgba(39, 110, 204, .5); } .buttonBlue:hover { background: #357bd8; } /* Ripples container */ .ripples { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; background: transparent; } /* Ripples circle */ .ripplesCircle { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); opacity: 0; width: 0; height: 0; border-radius: 50%; background: rgba(255, 255, 255, 0.25); } .ripples.is-active .ripplesCircle { animation: ripples .4s ease-in; } /* Ripples animation */ @keyframes ripples { 0% { opacity: 0; } 25% { opacity: 1; } 100% { width: 200%; padding-bottom: 200%; opacity: 0; } } footer { text-align: center; } footer p { color: #888; font-size: 13px; letter-spacing: .4px; } footer a { color: #4a89dc; text-decoration: none; transition: all .2s ease; } footer a:hover { color: #666; text-decoration: underline; } footer img { width: 80px; transition: all .2s ease; } footer img:hover { opacity: .83; } footer img:focus , footer a:focus { outline: none; }
  1. Create src/index.html file with the following content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Getting started with Firebase Auth</title> </head> <body> <div id="login"> <div class="header"> <h3>Getting Started with Firebase Auth</h3> </div> <form> <div class="group"> <input id="txtEmail" type="email"> <label>Email</label> </div> <div class="group"> <input id="txtPassword" type="password"> <label>Password</label> </div> <div id="divLoginError" class="group"> <div id="lblLoginErrorMessage" class="errorlabel">Error message</div> </div> <button id="btnLogin" type="button" class="button buttonBlue">Log in</button> <button id="btnSignup" type="button" class="button buttonBlue">Sign up</button> </form> </div> <div id="app"> <div class="header"> <h3>Welcome to Your Amazing App</h3> </div> <form> <div class="group"> <div id="lblAuthState" class="authlabel"></div> </div> <button id="btnLogout" type="button" class="button buttonBlue">Log out</button> </form> </div> <footer> <a href="https://firebase.google.com/" target="_blank"><img src="https://firebase.google.com/images/brand-guidelines/logo-standard.png" alt="Firebase logo"></a> </footer> <script src="main.js"></script> </body> </html>

The next step is to enhance the application to support webpack.

Task 3. Adding a Webpack configuration

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

  1. Return to the firebase-project folder:
cd ~/firebase-project
  1. Create a 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: '[name].js', assetModuleFilename: '[name][ext]', }, watch: false, module: { rules: [ { test: /\.css$/i, use: [ 'style-loader', 'css-loader' ] } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', filename: 'index.html', inject: false }) ], }
  1. Install webpack npm packages:
npm install webpack webpack-cli --save-dev
  1. Install html-webpack-plugin, style-loader and css-loader :
npm install --save-dev style-loader css-loader html-webpack-plugin
  1. Edit the package.json file:

  2. Replace the "main": "index.js" entry with the following line in the package.json:

"private": "true",
  1. Add a build script to the package.json:
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack" },
  1. The package.json should now look similar to the following:
{ "name": "firebase-project", "version": "1.0.0", "description": "", "private": "true", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "firebase": "^9.19.1" }, "devDependencies": { "css-loader": "^6.7.3", "html-webpack-plugin": "^5.5.0", "style-loader": "^3.3.2", "webpack": "^5.79.0", "webpack-cli": "^5.0.1" } }
  1. Run the application build from the command line:
npm run build

Output Example

> firebase-project@1.0.0 build > webpack asset main.js 1.6 MiB [emitted] (name: main) asset index.html 1.46 KiB [emitted] runtime modules 1.17 KiB 6 modules modules by path ./node_modules/ 578 KiB modules by path ./node_modules/style-loader/dist/runtime/*.js 5.84 KiB 6 modules modules by path ./node_modules/@firebase/ 543 KiB 6 modules modules by path ./node_modules/firebase/ 897 bytes 2 modules modules by path ./node_modules/css-loader/dist/runtime/*.js 2.74 KiB 2 modules modules by path ./node_modules/idb/build/*.js 10.8 KiB 2 modules + 1 module modules by path ./src/ 15.7 KiB modules by path ./src/*.js 3.7 KiB ./src/index.js 2.31 KiB [built] [code generated] ./src/ui.js 1.4 KiB [built] [code generated] modules by path ./src/*.css 12 KiB ./src/styles.css 1.12 KiB [built] [code generated] ./node_modules/css-loader/dist/cjs.js!./src/styles.css 10.9 KiB [built] [code generated] webpack 5.86.0 compiled successfully in 1536 ms

The application is successfully built and the next step is to the Firebase functionality.

Task 4. Testing the application

Testing the application requires it to be run in the current environment.

  1. Serve html from the dist directory on port 8080 :
python3 -m http.server 8080 --directory dist
  1. Open the Cloud Shell web preview on port 8080:

Example Output

Firebase Authentication application login Note:

At this point a user account does not exist.

To add a new user, use the Sign Up option to register the account credentials in Firebase Authentication.

  1. Enter the following Email address:
tester1@tester.com
  1. Enter the following Password:
Password123
  1. Click the Sign up button:

Example Output

Firebase Authentication Logged In
  1. Click the Logout button:
Note:

At this point a user has now been created in Firebase with the credentials provided. To verify return to the Firebase project and view the Authentication Users list.

  1. Enter the following Email address:
tester1@tester.com
  1. Enter the following Password:
Password123
  1. Click the Login button:

Example Output

Firebase Authentication Logged In

At this point the backend Firebase project is being referenced. Each time a user is registered it will be added to the Firebase project.

Registered users will now be able to Log into the application.

Congratulations!

In just 30 minutes, you developed a solid understanding of Firebase on the Web and the key features. You learned about installing Firebase Authentication, creating and running an authentication application. You are now ready to take more labs.

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 Cloud Firestore: Getting started with Cloud Firestore 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 08, 2023

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