Firebase Integration with Web


Firebase was started by Google in 2014, providing backend services to its users. It provides different kinds of high-quality services which we can use to develop mobile and web applications. For example, it provides a real-time database, user authentication, cloud storage, etc. Furthermore, it also provides analytics to analyze the application’s traffic. It is more popular due to its quick setup.

In this tutorial, we will learn to integrate Firebase authentication into the one-page web application.

Users should follow the steps below to set up the Firebase account and integrate it with a single-page web application.

  • Step 1 − First, Go to the website of Firebaseand create an account.

  • Step 2 − Now, go the https://console.firebase.google.com/u/0/ to open a Firebase console.

  • Step 3 − Now, click on the ‘create project’ button to start creating a new project.

  • Step 4 − Here, fill in the required details and click on the ‘continue’ button. We are creating a ‘test’ application here.

  • Step 5 − Select the preferred location, accept the terms and conditions and click on the ‘create project’ button. After that, please wait until it creates a project for you.

  • Step 6 − It will redirect you to the below page. Here, click on the ‘Authentication’ card element. After that, click on the ‘get started’ button.

  • Step 7 − Go to the ‘sign-in methods’ tab, and click on the ‘Email/password’ field. After that, enable the ‘email/password’ method, and click on the ‘save’ button. Users can also enable other ways to authenticate your web application from here.

  • Step 8 − Now, click on the ‘project settings’ and get the API and project Id from there. Store it somewhere. We will use it in the example below.

Creating a Single Page Static Application

Now, the setup of the Firebase project is done. Next, we will create a single-page static application.

Steps

  • Step 1 − Add the Firebase in either way to your project. Here, we have added using the CDN. Developers can also use the SDK based on the project they are currently working on.

  • Step 2 − Now, build a simple HTML template that inputs email and password. Also, add the signup, login and logout buttons.

  • Step 3 − In JavaScript, initialize the Firebase configuration with the API key and project id.

  • Step 4 − Use the onAuthStateChanged() method to print a message when the authentication state changes.

  • Step 5 − Use the auth() method of Firebase to initialize the authentication.

  • Step 6 − Now, create an addUsers() function to add users to the Firebase. Access the email and password in the function, and use the createUserWithEmailAndPassword() method to add users to Firebase.

  • Step 7 − Now, create a logIn() function, and use the signInWithEmailAndPassword() method to log in to the application using the email and password.

  • Step 8 − Also, create a logout() function which uses the signOut() method to end the current session.

Example

In the example below, we have created a simple form with two input fields. Whenever the user clicks the signUp button, it invokes the addUsers() function, which adds users to the Firebase. If the user enters a weak password or the wrong email address, Firebase returns an error.

Furthermore, when the user clicks on the login button, it invokes the ‘login()’ function, which allows users to sign in to the application. If users enter the wrong password or emails, Firebase returns an error. When a user clicks the signOut button, it executes the signOut() function, ending the current sessions.

Note − Here, developers require to change the API key, Project ID, and project Domain according to their project. The below credentials are generated only for testing purpose.

<html>
<head>
   <script src = "https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js">
   </script>
   <script src = "https://www.gstatic.com/firebasejs/8.2.7/firebase-auth.js">
   </script>
   <style>
      button {
         width: 100px;
         height: auto;
         padding: 5px 10px;
         background-color: aqua;
         border: 2px solid green;
         border-radius: 12px;
      }
   </style>
</head>
<body>
   <h2>
      Using the <i> Firebase auth </i> to add authentication in a single page static website.
   </h2>
   <div class = "container">
      <h2>Enter the email and password below.</h2>
      <input type = "email" placeholder = "abcd@gamil.com" id = "email" />
      <br /> <br />
      <input type = "password" placeholder = "Add password" id = "password" />
      <br /> <br />
      <button onclick = "addUsers()" id = "signUp">
         SignUp
      </button>
      <button onclick = "login()" id = "logIp">
         SignIn
      </button>
      <button onclick = "logout()" id = "logOut">
         SignOut
      </button>
      <br> <br>
      <div id = "output"> </div>
   </div>
   <script>
      let output = document.getElementById('output');
      // Your web app's Firebase configuration
      var initialConfig = {
         apiKey: "AIzaSyBsYILuhF4wOGOe0rFhPudhVWO3cGh2z18", // change API keu
         authDomain: "localhost", // change domain
         projectId: "test-application-45005", // change project Id
      };
      
      // Initialize Firebase
      firebase.initializeApp(initialConfig);
      const authenticate = firebase.auth();
      
      // Check if there are any active users
      firebase.auth().onAuthStateChanged((user) => {
         if (user) {
            var email = user.email;
            output.innerHTML = "Active user is " + email + "<br>";
         } else {
            output.innerHTML = "No active users" + "<br>";
         }
      });
      
      // add users
      function addUsers() {
         var email = document.getElementById("email").value;
         var password = document.getElementById("password").value;
         
         // adding users via the promise
         authenticate.createUserWithEmailAndPassword(
            email,
            password
         ).then((userCredential) => {
            output.innerHTML = "User added successfully and user id is " + userCredential.user.uid + "<br>";
         }).catch((e) => {
            output.innerHTML = "Some error occurred - " + e.message + "<br>";
         });
      }
      
      // login function
      function login() {
         var email = document.getElementById("email").value;
         var password = document.getElementById("password").value;
         authenticate.signInWithEmailAndPassword(
         email, password).then((userCredential) => {
            output.innerHTML = "User login successfully and user id is " + userCredential.user.uid + "<br>";
         }).catch((e) => {
            output.innerHTML = "Some error occurred - " + e.message + "<br>";
         });
      }
      
      // logout currently logged-in user
      function logout() {
         authenticate.signOut();
         output.innerHTML = "User logout successfully";
      }

   </script>
</body>
</html>

Users learned to integrate the Firebase with the web application. It hardly takes 15 minutes to integrate Firebase with any web application for an experienced developer. Also, it gives an error if users enter a weak password while signIn into the application, and it manages all other stuff about which developers don’t need to worry.

Also, developers can use the database of the Firebase with any web or mobile application.

Updated on: 24-Apr-2023

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements