Creating a Simple Login and Signup Page with Firebase Authentication by Pure Javascript

Creating a Simple Login and Signup Page with Firebase Authentication by Pure Javascript
2024-11-10•Basic•6 min

Creating a secure and responsive login and signup page is a critical part of many applications. Here, we'll walk through setting up a Firebase authentication form for both login and signup functions. The code includes a visually appealing layout and the use of Firebase to handle user authentication.

Step 1: Setting Up Firebase

To get started, you'll need a Firebase project. Firebase Authentication allows you to manage users securely and provides various methods of authentication, including email and password.

  • Go to Firebase Console.
  • Click on Add Project and follow the steps to create a new project.
  • Go to Project Settings > General and copy your Firebase configuration object. You'll need this to initialize Firebase in your app.
  • Step 2: HTML & CSS Structure

    Our HTML structure provides two main sections: one for login and one for signup. We'll use a checkbox to toggle between these two views, creating a smooth transition effect.

    Here’s the HTML and CSS code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Sign up / Login Form</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            /* Body and main container styling */
            body {
                margin: 0;
                padding: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
                font-family: 'Jost', sans-serif;
                background: linear-gradient(to bottom, #0f0c29, #302b63, #24243e);
            }
    
            /* Main form container */
            .main {
                width: 350px;
                height: 500px;
                overflow: hidden;
                background: url('image_url_here') no-repeat center/cover;
                border-radius: 10px;
                box-shadow: 5px 20px 50px #000;
            }
    
            /* Styling for form elements */
            input {
                width: 60%;
                height: 10px;
                background: #e0dede;
                margin: 20px auto;
                padding: 12px;
                border: none;
                outline: none;
                border-radius: 5px;
            }
    
            /* Button styling */
            button {
                width: 60%;
                height: 40px;
                margin: 10px auto;
                color: #fff;
                background: #573b8a;
                font-size: 1em;
                font-weight: bold;
                border: none;
                border-radius: 5px;
                cursor: pointer;
            }
        </style>
    </head>
    <body>

    This CSS will give your form a minimalistic, clean look with a visually appealing background gradient. The main div holds our form elements and applies some styling to keep everything centered on the page.

    Step 3: Adding Firebase Authentication Logic

    Firebase authentication uses the firebase.auth library. Here’s how to integrate Firebase into our app and handle user signup and login.

    Add the Firebase configuration from your Firebase Console, then initialize Firebase in your <script> block:

    const firebaseConfig = {
        apiKey: "YOUR_API_KEY",
        authDomain: "YOUR_AUTH_DOMAIN",
        projectId: "YOUR_PROJECT_ID",
        storageBucket: "YOUR_STORAGE_BUCKET",
        messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
        appId: "YOUR_APP_ID"
    };
    
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    const auth = firebase.auth();

    Step 4: Signup and Login Functions

    The following JavaScript code handles the signup and login functions:

    The signUp function allows new users to create an account by entering their email and password. If successful, it stores the uid (unique user ID) in a cookie and redirects the user to the main page.

    async function signUp(event) {
        event.preventDefault();
        const email = document.querySelector('input[name="email"]').value;
        const password = document.querySelector('input[name="pswd"]').value;
    
        try {
            const UserCredential = await auth.createUserWithEmailAndPassword(email, password);
            const uid = UserCredential.user.uid;
            console.log("User signed up: ", uid);
    
            // Set uid in a cookie
            document.cookie = `uid=${uid}; max-age=${365 * 24 * 60 * 60}; path=/;`;
    
            // Redirect to main page after signup
            window.location.href = '/mainPage.html';
        } catch (error) {
            console.log("Error: ", error.message);
        }
    }

    The LoginUser function authenticates existing users by checking the entered email and password against Firebase. If successful, it sets the uid in a cookie and redirects the user.

    async function LoginUser(event) {
        event.preventDefault();
        const email = document.querySelector('input[name="loginemail"]').value;
        const password = document.querySelector('input[name="loginpswd"]').value;
    
        try {
            const UserCredential = await auth.signInWithEmailAndPassword(email, password);
            const uid = UserCredential.user.uid;
            console.log("User logged in successfully with UID: ", uid);
    
            // Set uid in a cookie
            document.cookie = `uid=${uid}; max-age=${365 * 24 * 60 * 60}; path=/;`;
    
            // Redirect to main page after login
            window.location.href = '/mainPage.html';
        } catch (error) {
            console.log("Error: ", error.message);
        }
    }

    Step 5: Event Listeners for Form Submission

    After defining the signup and login functions, we need to set up event listeners that trigger these functions when the forms are submitted:

    document.addEventListener('DOMContentLoaded', () => {
        document.querySelector('.signup form').addEventListener('submit', signUp);
        document.querySelector('.login form').addEventListener('submit', LoginUser);
    });

    With Firebase’s authentication services, you can build a secure, functional, and visually appealing login/signup system with ease. Firebase takes care of complex authentication processes like email verification, password reset, and error handling, leaving you to focus on designing a great user experience.

    Here is the Full Code :

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title>Sign up / Login Form</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            body {
                margin: 0;
                padding: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
                font-family: 'Jost', sans-serif;
                background: linear-gradient(to bottom, #0f0c29, #302b63, #24243e);
            }
    
            .main {
                width: 350px;
                height: 500px;
                background: red;
                overflow: hidden;
                background: url("https://doc-08-2c-docs.googleusercontent.com/docs/securesc/68c90smiglihng9534mvqmq1946dmis5/fo0picsp1nhiucmc0l25s29respgpr4j/1631524275000/03522360960922298374/03522360960922298374/1Sx0jhdpEpnNIydS4rnN4kHSJtU1EyWka?e=view&authuser=0&nonce=gcrocepgbb17m&user=03522360960922298374&hash=tfhgbs86ka6divo3llbvp93mg4csvb38") no-repeat center/ cover;
                border-radius: 10px;
                box-shadow: 5px 20px 50px #000;
            }
    
            #chk {
                display: none;
            }
    
            .signup {
                position: relative;
                width: 100%;
                height: 100%;
            }
    
            label {
                color: #fff;
                font-size: 2.3em;
                justify-content: center;
                display: flex;
                margin: 50px;
                font-weight: bold;
                cursor: pointer;
                transition: .5s ease-in-out;
            }
    
            input {
                width: 60%;
                height: 10px;
                background: #e0dede;
                justify-content: center;
                display: flex;
                margin: 20px auto;
                padding: 12px;
                border: none;
                outline: none;
                border-radius: 5px;
            }
    
            button {
                width: 60%;
                height: 40px;
                margin: 10px auto;
                justify-content: center;
                display: block;
                color: #fff;
                background: #573b8a;
                font-size: 1em;
                font-weight: bold;
                margin-top: 30px;
                outline: none;
                border: none;
                border-radius: 5px;
                transition: .2s ease-in;
                cursor: pointer;
            }
    
            button:hover {
                background: #6d44b8;
            }
    
            .login {
                height: 460px;
                background: #eee;
                border-radius: 60% / 10%;
                transform: translateY(-180px);
                transition: .8s ease-in-out;
            }
    
            .login label {
                color: #573b8a;
                transform: scale(.6);
            }
    
            #chk:checked~.login {
                transform: translateY(-500px);
            }
    
            #chk:checked~.login label {
                transform: scale(1);
            }
    
            #chk:checked~.signup label {
                transform: scale(.6);
            }
        </style>
        <script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-app-compat.js"></script>
        <script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-auth-compat.js"></script>
        <script>
            const firebaseConfig = {
                apiKey: "AIzaSyBGbWREYVn-xxxxxxxxxxxxx",
                authDomain: "xxxxx-xxxx.firebaseapp.com",
                databaseURL: "https://xxxxxx-xxxxxx-default-rtdb.firebaseio.com",
                projectId: "xxxxxx-xxxxx",
                storageBucket: "xxxxxx-xxxxxx.appspot.com",
                messagingSenderId: "00000000000",
                appId: "1:0000000000000:web:000000000000000",
                measurementId: "x-xxxxxxxxxx"
            };
            // Initalize Firebase
            firebase.initializeApp(firebaseConfig);
            const auth = firebase.auth();
    
            // Sign Up Function
            async function signUp(event) {
                event.preventDefault();
                const email = document.querySelector('input[name="email"]').value;
                const password = document.querySelector('input[name="pswd"]').value;
    
                try {
                    const UserCredenial = await auth.createUserWithEmailAndPassword(email, password);
                    const uid = UserCredenial.user.uid;
    
                    console.log("User signed up : ", uid);
    
                    // Set the uid as a permanent cookie
                    document.cookie = `uid=${uid}; max-age=${365 * 24 * 60 * 60}; path=/;`;
    
                    // Redirect to main page after login
                    window.location.href = '/mainPage.html'
                }
                catch (error) {
                    console.log("error : ", error.message);
                }
            }
    
            // Login Function
    
            async function LoginUser(event) {
                event.preventDefault();
                const email = document.querySelector('input[name="loginemail"]').value;
                const password = document.querySelector('input[name="loginpswd"]').value;
    
                try {
                    const UserCredenial = await auth.signInWithEmailAndPassword(email, password);
                    const uid = UserCredenial.user.uid;
    
                    console.log("User Logged In Sucessfully with UID : ", uid);
    
                    // Set the uid as a permanent cookie
                    document.cookie = `uid=${uid}; max-age=${365 * 24 * 60 * 60}; path=/;`;
    
                    // Redirect to main page after login
                    window.location.href = '/mainPage.html'
                }
                catch (error) {
                    console.log("error : ", error.message);
                }
    
            }
    
            document.addEventListener('DOMContentLoaded', () => {
                document.querySelector('.signup form').addEventListener('submit', signUp);
                document.querySelector('.login form').addEventListener('submit', LoginUser);
            })
        </script>
    </head>
    
    <body translate="no">
        <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500&amp;display=swap" rel="stylesheet">
    
        <div class="main">
            <input type="checkbox" id="chk" aria-hidden="true">
    
            <div class="signup">
                <form>
                    <label for="chk" aria-hidden="true">Sign up</label>
                    <input type="text" name="txt" placeholder="User name" required="">
                    <input type="email" name="email" placeholder="Email" required="">
                    <input type="password" name="pswd" placeholder="Password" required="">
                    <button>Sign up</button>
                </form>
            </div>
    
            <div class="login">
                <form>
                    <label for="chk" aria-hidden="true">Login</label>
                    <input type="email" name="loginemail" placeholder="Email" required="">
                    <input type="password" name="loginpswd" placeholder="Password" required="">
                    <button>Login</button>
                </form>
            </div>
        </div>
    
    </body>
    
    </html>

    In this blog, we've covered:

  • Setting up Firebase and integrating it into your HTML.
  • Writing JavaScript functions to handle user signup and login.
  • Using CSS to enhance the form's aesthetic.
  • By following these steps, you can create a beautiful, functional login and signup form for any web application.

    Happy Coding!