Author Photo
Christopher Unum I am a software Developer, I write web development tutorials, I also mentor aspiring web developers. s

how to create login and registration forms with session handling using firebase authentication on the web

Sign Up

Email

Confirm Email

Password

Sign In

Email

Password

Forgot Password

Logged In



Authenticating users and handling user sessions is a vital part of modern-day applications. when I was still a novice at writing a web application, I really struggled with finding a proper way to handle user authentication and sessions, well if you are still in that loop, this might be your chance to get out. In this tutorial, we will create an app that registers user and logs them in with their email and password using Firebase Authentication

Prerequisite

Basic knowledge of Html, CSS and JavaScript (ES 6) is required to fully understand the concepts in this tutorial.

Html

We will be creating a single page app that will contain the Sign-Up, Sign-In and Homepage sections. Below is the Html code we will be working with.

<div class="forms-out">
    <div class="forms-in">
     <div id="registration-page" class="hide">
        <button id="show-login">Sign In</button>
        <h3>Sign Up</h3>
        Email <br />
        <input type="email" id="registration-email" /><br />
        Confirm Email <br />
        <input
        type="email"
        id="registration-reemail"
        autocomplete="disable"
        /><br />
        Password <br />
        <input type="password" id="registration-password" /><br />
        <center><button id="register">Sign Up</button></center>
     </div>

     <div id="login-page">
        <button id="show-register">Sign Up</button>
        <h3>Sign In</h3>
        Email <br />
        <input type="email" id="login-email" /><br />
        Password <br />
        <input type="password" id="login-password" /><br />
        <p id="forgot-password">Forgot Password</p>
        <center><button id="login">Sign In</button></center>
     </div>

     <div id="homepage" class="hide">
        <button id="signout">Sign Out</button>
        <h3>Logged In</h3>
     </div>
    </div>
</div>

CSS

Styling the Html

.forms-out {
margin0 auto;
font-family"Fira Sans"sans-serif;
padding15px 0;
}

.forms-in {
width93%;
margin0 auto;
colorwhite;
padding15px 0;
}

.forms-in div {
padding30px 20px;
max-width350px;
margin0 auto;
background#168ab8;
border-radius5px;
margin-bottom15px;
}

.forms-in h3 {
text-aligncenter;
}

.forms-in input {
bordernone;
width100%;
margin-bottom15px;
padding10px;
box-sizingborder-box;
border-radius3px;
}

.forms-in button {
bordernone;
padding7px 20px;
background#e8f8ff;
color#168ab8;
border-radius4px;
cursorpointer;
font-weightbold;
}

.forms-in button:hover {
opacity0.7;
}

.hide {
displaynone;
}

#forgot-password {
text-aligncenter;
font-size13 px;
cursorpointer;
}

#forgot-password:hover {
opacity0.7;
}

 

Add Firebase to your JavaScript project

Before you can start using Firebase in your web project, you need to create a Firebase project to connect to your app. To create your Firebase project, click on this link to get instructions. 

You also need to enable Email/Password sign-in. To do this, you need to go to your Firebase Console, open authentication section, then click on the sign-in method tab and enable Email/Password sign-in method. The image below has Email/Password sign-in method enabled


If you are done with creating your Firebase Project and have enabled Password/Email, then you can start building your app.

Below is our Firebase Initialization Code with Firebase Authentication SDK

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use-->
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-auth.js"></script>

<script>
    // Your web app's Firebase configuration
    var firebaseConfig = {
    apiKey: "AIzaSyDHg0VrivE3C9A7jvzRu7lQgudLvcD_Fxk",
    authDomain: "registration-cf470.firebaseapp.com",
    databaseURL: "https://registration-cf470.firebaseio.com",
    projectId: "registration-cf470",
    storageBucket: "registration-cf470.appspot.com",
    messagingSenderId: "921371494542",
    appId: "1:921371494542:web:259209b868c843b08ea1df",
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
</script>

JavaScript

//invokes firebase authentication.

const auth = firebase.auth();
document.querySelector("#show-register").addEventListener("click", () => {
showRegistration();
});

const showRegistration = () => {
document.querySelector("#registration-page").classList.remove("hide");
document.querySelector("#login-page").classList.add("hide");
document.querySelector("#homepage").classList.add("hide");
};

document.querySelector("#show-login").addEventListener("click", () => {
showLogin();
});

const showLogin = () => {
document.querySelector("#registration-page").classList.add("hide");
document.querySelector("#login-page").classList.remove("hide");
document.querySelector("#homepage").classList.add("hide");
};

document.querySelector("#signout").addEventListener("click", () => {
signOut();
});

const register = () => {
const email = document.querySelector("#registration-email").value;
const reemail = document.querySelector("#registration-reemail").value;
const password = document.querySelector("#registration-password").value;

if (email.trim() == "") {
    alert("Enter Email");
else if (password.trim().length < 7) {
    alert("Password must be at least 7 characters");
else if (email != reemail) {
    alert("emails do not match");
else {
    auth
    .createUserWithEmailAndPassword(email, password)
    .catch(function (error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        alert(errorMessage);
        // ...
    });
}
};

document.querySelector("#register").addEventListener("click", () => {
register();
});

//register when you hit the enter key
document
.querySelector("#registration-password")
.addEventListener("keyup", (e) => {
    if (event.keyCode === 13) {
    e.preventDefault();

    register();
    }
});

const login = () => {
const email = document.querySelector("#login-email").value;
const password = document.querySelector("#login-password").value;

if (email.trim() == "") {
    alert("Enter Email");
else if (password.trim() == "") {
    alert("Enter Password");
else {
    authenticate(email, password);
}
};

document.querySelector("#login").addEventListener("click", () => {
login();
});

//sign in when you hit enter
document
.querySelector("#login-password")
.addEventListener("keyup", (e) => {
    if (event.keyCode === 13) {
    e.preventDefault();

    login();
    }
});

const authenticate = (email, password) => {
const auth = firebase.auth();
auth.signInWithEmailAndPassword(email, password);
firebase
    .auth()
    .signInWithEmailAndPassword(email, password)
    .catch(function (error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    alert(errorMessage);
    });
};

const showHomepage = () => {
document.querySelector("#registration-page").classList.add("hide");
document.querySelector("#login-page").classList.add("hide");
document.querySelector("#homepage").classList.remove("hide");
};

const signOut = () => {
firebase
    .auth()
    .signOut()
    .then(function () {
    location.reload();
    })
    .catch(function (error) {
    alert("error signing out, check network connection");
    });
};

auth.onAuthStateChanged((firebaseUser) => {
if (firebaseUser) {
    showHomepage();
}
});

document
.querySelector("#forgot-password")
.addEventListener("click", () => {
    const email = document.querySelector("#login-email").value;
    if (email.trim() == "") {
    alert("Enter Email");
    } else {
    forgotPassword(email);
    }
});

const forgotPassword = (email) => {
auth
    .sendPasswordResetEmail(email)
    .then(function () {
    alert("email sent");
    })
    .catch(function (error) {
    alert("invalid email or bad network connection");
    });
};

The complete source code

 Click this link to get the complete source code of this tutorial.

Conclusion

Keeping track of your users and handling user session has really been made easy with Firebase Authentication. There are other sign-in methods associated with Firebase Authentication like Google sign-in, facebook sign-in, github sign-in and lots more. I Hope you all learnt a lot from this tutorial, see you in the next.