OKORO EMMANUEL NZUBE
10 min readJan 7, 2022

--

HOW TO ADD FIREBASE AUTHENTICATION SERVICE TO YOUR PROJECT, TO SIGN UP AND LOGIN A USER.

https://firebase.google.com/docs/auth

Hello everyone, welcome. Today we will be learning how we can use the firebase authentication service to sign up and log in a user, but before we begin we will be looking at a brief introduction to firebase and what it is all about.

WHAT IS FIREBASE

Firebase is a complete backend solution, it provides developers with a variety of tools and services to help them build and run successful apps.

Just like we stated in the definition, firebase provides developers with a variety of tools and services, and today we will be learning about one of the services which firebase provides. So we will be looking at the firebase authentication service.

FIREBASE AUTHENTICATION

According to the firebase documentation;

firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more, etc.

To learn more about firebase authentication: https://firebase.google.com/docs/auth

Today I will be showing you how to add a firebase authentication service to sign up and log in a user, from our front-end using simple Html and JavaScript. Let us dive right into it.

Firstly, create a folder, then open the folder you created in your code editor. Create your Html files in my case I used index.html and I will be using my index.html to run my JavaScript code also.

HOW TO ADD FIREBASE TO YOUR PROJECT.

Go to the firebase website, when the site opens you will see “Get started” or “Go to Console” (located at the top right-hand corner), click on any of them and it will take you to the firebase console. Click on “create a project”, then enter your project name, make sure to disable Google Analytics (optional), accept the firebase terms and conditions then continue, continue clicking continue in each stage (that’s quite simple) till your project is ready.

Your project overview will be displayed like this;

Note: As time goes on the environment might not be the same, so don’t be bothered if your own environment is not like this.

I named my firebase project “firebase auth” which you can see clearly. We will be using the authentication for the web, so we go ahead and click that icon that looks like this </>. Input any name of your choice at that register app then click on register app.

You will see add firebase SDK. Here are two ways of installing firebase to your project, either by the use of npm or the use of a <script> tag. We will be making use of a <script> tag. Click on the <script> tag option. Copy the scripts and paste them in your project before your closing body tag like this;

<script type=”module”>// Import the functions you need from the SDKs you needimport { initializeApp } from “https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js";// TODO: Add SDKs for Firebase products that you want to use// https://firebase.google.com/docs/web/setup#available-libraries// Your web app’s Firebase configurationconst firebaseConfig = {apiKey: “###############……………”,authDomain: “###############……………”,projectId: “###############……………,storageBucket: “###############……………”,messagingSenderId: ###############……………,appId: “###############……………”};// Initialize Firebaseconst app = initializeApp(firebaseConfig);</script></body>

HOW TO IMPORT THE FIREBASE AUTHENTICATION SERVICE TO YOUR PROJECT

After you have copied the scripts to your code editor, click on continue to console, you should see a place they wrote build (that should be by the left side of the screen), click on “Build” you will see a dropdown of firebase services that looks like this;

firebase services

We are interested in the authentication service, so we click on it, then click on get started, you should see lots of sign-in methods like this;

firebase authentication sign in methods

We will be using the email and password sign-in method, click on email and password, enable it, and then save. You should see a help button like this “?” at the top right-hand side, click on it then click on Authentication Developer docs or go to docs and then click “Bulid”, you will see these;

Click on web, it is located on the left-hand side, click get started, then scroll down to where they wrote sign up new user (like the image above). Copy the import code which should look like these;

import { getAuth, creatUserWithEmailAndPassword } from “firebase/auth”;

Paste it in your <script> tag below the first import we have there. Note that the first import looks like these;

import { initializeApp } from “https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js"

Do the same to the import for signing up a new user by changing that from “firebase/auth”; to

import { getAuth, creatUserWithEmailAndPassword } from “https://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js";

The reason for doing this is because the web browser will not understand such a command because firebase was not installed using the npm install firebase method in the terminal.

Next thing is to copy the const auth = getAuth ( ); and paste it into the <script> tag. The const auth = getAuth ( ); command is used to initialize the firebase authentication service to our project. By so doing we have successfully added the firebase authentication service to our project.

HOW TO SIGN UP A NEW USER TO OUR PROJECT

Go to your index.html, in the body tag create a sign-up form, for example, here is mine;

<form id=”signUp”><input type=”text” id=”username” placeholder=”username”>
<br>
<input type=”email” id=”email” placeholder=”email”><br>
<input type=”password” id=”password” placeholder=”password”>
<br>
<button type=”submit”>sign up</button>
</form>

In the <script> tag below write this;

const signUp = document.querySelector(“#signUp”);signUp.addEventListener(“submit”, (e) => {e.preventDefault();const username = document.getElementById(“username”).value;const email = document.getElementById(“email”).value;const password = document.getElementById(“password”).value;

Go to the firebase authentication get started for web, where you copied the import code for the authentication i.e

import { getAuth, creatUserWithEmailAndPassword } from “https://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js";

copy the code there which is this;

createUserWithEmailAndPassword(auth, email, password).then((userCredential) => {// Signed inconst user = userCredential.user;alert(“New User Created”);// …}).catch((error) => {const errorCode = error.code;const errorMessage = error.message;alert(errorMessage);// ..});

Then paste it in your script tag, between the signUp.addEventListener function, your code should look like these;

signUp.addEventListener(“submit”, (e) => {e.preventDefault();const username = document.getElementById(“username”).value;const email = document.getElementById(“email”).value;const password = document.getElementById(“password”).value;createUserWithEmailAndPassword(auth, email, password).then((userCredential) => {// Signed inconst user = userCredential.user;alert(“New User Created”);// …}).catch((error) => {const errorCode = error.code;const errorMessage = error.message;alert(errorMessage);// ..});});

Let me explain what I did, I created a variable const and gave it the name signUp with a value of document.querySelector(“#signUp”), the document.querySelector(“#signUp”) was used it select the particular id which I needed and in my case was the #signUp.

I called the signUp variable and gave it an addEventListener which takes in an argument of “submit” and a function of (e) => {}. Do not fail to notice the e.preventDefault( );, this prevents the event from refreshing whenever you click on submit button, where (e) is the event.

const username = document.getElementById(“username”).value;const email = document.getElementById(“email”).value;const password = document.getElementById(“password”).value;

From the code above, we created a variable using const username, const email, const password and we got all the input fields that we had already created in our Html using the document.getElementBy id( ) and we input the id of each input field that we created in our Html, and in my case, I gave them the id of “username”, “email”, “password” then .value which is to get the value of anything which was typed into the input field and was submitted.

I added an alert message to the code we copied from the firebase site alert(“New User Created”);. The alert message of “New User Created” will be displayed if the sign-up was successful but if not successful, the alert message of “errorMessage” will be displayed, for example here is mine;

sign-up successful
Error Message showing that user already existed.

From the images above, you will see an alert message of New user created (sign-up successful) and the alert message of Firebase: Error (auth/email-already-in-use) which shows the (errorMessage).

Lastly, if the sign-up was successful, go to your firebase project, at the authentication, you will see that the email which you filled when you signed-up has already been added, i.e you will see this;

sign-up completed.

Here is the code to the sign-up section: index.html

HOW TO LOG IN A USER

To login in an already signed-up user, go to the index.html code and create a login form, in my case I created a new HTML file and called it index2.html but if you still want to run your login on the same page with the sign-up, that is totally fine. So here is my code;

<form id=”loginform”><input type=”email” placeholder=”Email” id=”loginEmail” required><br><input type=”password” placeholder=”input your password” id=”loginPass” required><br><button type=”submit” id=”login”>log in</button></form>

To log in user, I created a database that I used in storing the users' last login date, and without creating the database, logging in user wouldn’t be possible. So I will be showing you how I created the database.

They are two ways to create a database using firebase, and that is with the use of Firestore database, or Realtime database, both databases are amongst the services which firebase provides, and for this project, I will be using the Realtime Database.

Before we go ahead, we need to know what the Realtime Database really is;

From the Firebase Realtime Database documentation,

The Firebase Realtime Database is a cloud-hosted NoSQL database that lets you store and sync data between your users in realtime.

To create a Realtime Database, go to your firebase project, click on “Realtime Database”, which should be on the left-hand side, below the authentication button. When it opens click on create Database, then run the Realtime Database in test mode first so you can access your project anytime without verification. After creating the database, go to your code editor then import the Realtime Database library by with;

import { getDatabase } from “https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js"; then initialize it with a variable, const database = getDatabase(app);

I gave my login form an id of loginForm, I created a variable const and gave it a name of loginForm with a value of document.querySelector(“#loginForm”)

I called the loginForm variable and gave it an addEventListener which takes in an argument of “submit” and a function of (e) => {}. (just like for the sign-up)

const email = document.getElementById(‘loginEmail’).valueconst password = document.getElementById(‘loginPass’).value

Go to your firebase authentication, where you copied the code for sign up, as you scroll down a little, you should see where they wrote “sign in existing user”, copy the code and also paste in your code editor, your code should look like these;

loginForm.addEventListener(‘submit’, (e) => {e.preventDefault();const email = document.getElementById(‘loginEmail’).valueconst password = document.getElementById(‘loginPass’).valuesignInWithEmailAndPassword(auth, email, password).then((userCredential) => {// Signed inconst user = userCredential.user;// …const dt = new Date();update(ref(database, ‘user/’ + user.uid), {last_login: dt,})alert(‘user loged in’);}).catch((error) => {const errorCode = error.code;const errorMessage = error.message;alert(‘Error loging in’);});});</script>From the code above, I used;const dt = new Date();update(ref(database, ‘user/’ + user.uid), {last_login: dt,})I created a variable and named it dt with a value of new Date(); then used;update(ref(database, ‘user/’ + user.uid), {last_login: dt,})

The code above shows when an existing user logs in to the site. Do not forget to reference it by adding set, update, and ref in the database import library like this;

import { getDatabase, set, ref, update } from “https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js";

Here is how my script code looks;

<script type=”module”>// Import the functions you need from the SDKs you needimport { initializeApp } from “https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js";import { getDatabase, set, ref, update } from “https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js";import { getAuth, signInWithEmailAndPassword } from “https://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js";// TODO: Add SDKs for Firebase products that you want to use// https://firebase.google.com/docs/web/setup#available-libraries// Your web app’s Firebase configurationconst firebaseConfig = {apiKey: “###############……………”,authDomain: “###############……………”,projectId: “###############……………,storageBucket: “###############……………”,messagingSenderId: ###############……………,appId: “###############……………”};// Initialize Firebaseconst app = initializeApp(firebaseConfig);const database = getDatabase(app);const auth = getAuth();const loginForm = document.querySelector(‘#loginform’);const user = auth.currentUser;loginForm.addEventListener(‘submit’, (e) => {e.preventDefault();const email = document.getElementById(‘loginEmail’).valueconst password = document.getElementById(‘loginPass’).valuesignInWithEmailAndPassword(auth, email, password).then((userCredential) => {// Signed inconst user = userCredential.user;// …const dt = new Date();update(ref(database, ‘user/’ + user.uid), {last_login: dt,})alert(‘user loged in’);}).catch((error) => {const errorCode = error.code;const errorMessage = error.message;alert(‘Error loging in’);});});</script>

When I run the code in my browser, the alert message of “user logged in” is displayed and when I check my database, the last login date is displayed as well.

User Login successful
user last_login date

Here is the code for this section:index2.html

Here is the code to the complete project: Firebase Authentication

CONCLUSION

The article above should give you a head start on how to add the firebase authentication service to your project, please read it carefully.

Note: Make sure you have a strong internet connection while using the Firebase services.

Happy Coding!!!

--

--