How to Make a Simple Login using Firebase, HTML, and CSS
Learn to build a simple, secure login system for your website using Firebase authentication.
In this guide, we'll walk you through the steps to create a simple login system using Firebase, HTML, and CSS.
Note: this guide assumes you are already familiar with the basics of HTML and CSS. I'll also be using VSCode as my main IDE.
Demo website and Full code.
What is Firebase?
Firebase is a platform developed by Google for creating mobile and web applications. It offers various tools and services, including authentication, real-time database, cloud storage, and more. In this tutorial, we'll focus on Firebase Authentication, which provides backend services to easily authenticate users using only client-side code.
Setting Up Firebase
Step 1: Create a Firebase Project
- Go to the Firebase Console:
- Visit Firebase Console.
- Click on "Add project" and follow the prompts to create a new project. Note that you will not be able to change the firebase project ID after you create your project. Enabling google analytics is optional but recommended.
- Register your app:
- Once your project is created, you will have different options depending on what type of app you're making (iOS, Android, web). If you're following along this tutorial, most likely you're making a web app, so click on the web icon (
</>
) to register your app. - Provide a name for your app and click "Register app".
- Once your project is created, you will have different options depending on what type of app you're making (iOS, Android, web). If you're following along this tutorial, most likely you're making a web app, so click on the web icon (
- Add Firebase SDK:
- Firebase will provide you with a configuration snippet. Copy this snippet and store it somewhere safe as we'll need it later.
Step 2: Enable Authentication
- Go to the Authentication section:
- In the Firebase Console, navigate to "Authentication" from the left menu.
- Click on the "Get Started" button.
- Enable Google Sign-In:
- Under the "Sign-in method" tab, enable the "Google" provider.
- Follow the prompts to set up Google Sign-In.
Setting Up the Project
Create a new directory for your project and create the following files:
index.html
style.css
app.js
HTML Structure
Let's start coding! Create a simple HTML structure for the login pages:
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Firebase Google Login</title> <link rel="stylesheet" href="style.css"> <script type="module" src="app.js" defer></script> </head> <body> <h1>My Awesome Sign In Page 🔥</h1> <div class="container"> <section id="whenSignedOut" class="form-container"> <button id="signInBtn" class="btn">Sign in with Google</button> </section> <section id="whenSignedIn" class="dashboard-container" hidden> <div id="userDetails"></div> <button id="signOutBtn" class="btn">Sign Out</button> </section> </div> </body> </html>
This file sets up the initial login page. It includes buttons for signing in and out, and sections that are shown or hidden based on the user's authentication state
- The
whenSignedOut
section contains a button to sign in with Google. - The
whenSignedIn
section contains user details and a sign-out button, hidden by default and shown when a user is signed in.
CSS Styling
Add some basic styling in style.css to make the forms look better.
body { font-family: Arial, sans-serif; display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; margin: 0; } .container { display: flex; justify-content: center; align-items: center; flex-direction: column; width: 50%; max-width: 400px; margin: 0 auto; } .form-container, .dashboard-container { background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); width: 100%; text-align: center; } h2 { margin-bottom: 20px; } button { width: 100%; padding: 10px; margin: 10px 0; background-color: #007bff; border: none; border-radius: 4px; color: white; font-size: 16px; cursor: pointer; } button:hover { background-color: #0056b3; }
We're not going to go in depth as to what the above CSS does exactly, but basically all it does is:
- Styles the body to center content and gives it a background color.
- Styles the container to center content with a max-width of 400 pixels.
- Adds styling for form containers and buttons for a clean design.
JavaScript Integration
Finally, our app.js
configures Firebase and adds authentication logic.
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js'; import { getAuth, signInWithPopup, GoogleAuthProvider, onAuthStateChanged, signOut } from 'https://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js'; // Your web app's Firebase configuration const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_PROJECT_ID.firebaseapp.com", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_PROJECT_ID.appspot.com", messagingSenderId: "YOUR_SENDER_ID", appId: "YOUR_APP_ID" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const auth = getAuth(app); const provider = new GoogleAuthProvider(); // Sign in function document.getElementById('signInBtn').addEventListener('click', () => { signInWithPopup(auth, provider) .then((result) => { console.log(result.user); }) .catch((error) => { console.error(error); }); }); // Sign out function document.getElementById('signOutBtn').addEventListener('click', () => { signOut(auth).then(() => { console.log('User signed out'); }).catch((error) => { console.error(error); }); }); // Listen to authentication state changes onAuthStateChanged(auth, (user) => { if (user) { document.getElementById('whenSignedIn').hidden = false; document.getElementById('whenSignedOut').hidden = true; document.getElementById('userDetails').textContent = `Hello, ${user.displayName}. Your UID is: ${user.uid}`; } else { document.getElementById('whenSignedIn').hidden = true; document.getElementById('whenSignedOut').hidden = false; } })
Our app.js
can be split into 4 different sections:
1. Firebase Configuration:
The JavaScript integration starts by importing the necessary Firebase modules for initializing the app and handling authentication. The Firebase configuration object contains the project's API key, authentication domain, project ID, storage bucket, messaging sender ID, and app ID. This configuration is used to initialize the Firebase app and get the authentication instance and GoogleAuthProvider.
const app = initializeApp(firebaseConfig); const auth = getAuth(app); const provider = new GoogleAuthProvider();
2. Sign In Function:
The sign-in function is set up by adding an event listener to the "Sign in with Google" button. When this button is clicked, it triggers the signInWithPopup function to sign in with Google. Upon a successful sign-in, the user's information is logged to the console. If there is an error during the sign-in process, the error is logged to the console.
document.getElementById('signInBtn').addEventListener('click', () => { signInWithPopup(auth, provider) .then((result) => { console.log('User signed in:', result.user); }) .catch((error) => { console.error('Error during sign in:', error); }); });
3. Sign out Function:
Similarly, the sign-out function is set up by adding an event listener to the "Sign Out" button. When this button is clicked, it triggers the signOut function to sign the user out. Upon a successful sign-out, a message is logged to the console. If there is an error during the sign-out process, the error is logged to the console.
It's generally good practice to have a try-catch block for signing in and signing out as unexpected errors do arise sometimes, and you want to have a way of handling the error without crashing your app.
document.getElementById('signOutBtn').addEventListener('click', () => { signOut(auth) .then(() => { console.log('User signed out'); }) .catch((error) => { console.error('Error during sign out:', error); }); });
4. Authentication State Listener:
This is where the actual UI control, depending on whether the user is signed in, takes place.
The authentication state listener uses the onAuthStateChanged function to listen for changes in the user's authentication state. If a user is signed in, the user's details (name and UID) are displayed, and the signed-in UI elements are shown while hiding the signed-out elements. If no user is signed in, the signed-in UI elements are hidden, and the signed-out UI elements are shown.
Our code ensures that the correct UI elements are shown based on whether the user is signed in or not. It uses Firebase's authentication features to manage sign-in and sign-out processes and listens for authentication state changes to dynamically update the UI.
Firebase Configuration
Replace the placeholders in the Firebase configuration object with the actual values from your Firebase project settings that you saved earlier. If you lost your Firebase config, you can retrieve them again in your project's settings:
Running your code
One easy way to set up a local development server is to use the Live Server extension in VSCode. If you don't have it already, head over to the Extensions marketplace and install the Live Server extension:
After doing so, head over to index.html
and click on "Open with Live Server" (you need to right click first).
Depending on how it is set up, your web page may open to http://localhost:5500/index.html
, http://127.0.0.1:5500/index.html
, or something else. Make sure to change the URL to http://localhost:5500
; otherwise, your authentication will not work.
The reason being is that only "localhost" is an authorized domain (by default). Google authentication can only occur under authorized domains, so if you want to use Firebase authentication, make sure you're either in one of the default domains (as with localhost) or you register your domain in Settings
.
Click the "Sign in with Google" button to authenticate with your Google account.
If successful, you'll be able to see your name and unique User ID (UID), as well as the option to log out.
Every user is assigned a unique UID that identifies that user. Although it isn't much use in this mini project, it can be extremely useful if your app stores data about each individual user with Firebase Firestore (Firebase's database, another add-on).
Hosting 🌐
Firebase makes hosting on its platform extremely simple. If you decide to host your website on another platform such as Vercel, check out this guide.
Otherwise, head over to the Firebase hosting module to get started.
First, you need to install the Firebase Command Line Interface (CLI) tools. Open your terminal or command prompt and run the following command:
npm install -g firebase-tools
If you don't have Node JS installed (which is required to use npm) download it at nodejs.org.
Once the Firebase CLI is installed, log in to your Firebase account by running:
firebase login
Follow the prompts to complete the login process.
Then, if you haven't already, navigate to the root directory of your project in the terminal and initialize Firebase in your project directory:
firebase init
Select the following options during the initialization process:
- Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys.
- Existing project: Select your Firebase project that you want to host (this one!).
- Public directory: Set it to . (the current directory) or specify a directory where your index.html and other files are located (if you chose to use a different directory).
- Single-page app: Choose yes.
- Set up automatic builds and deploys with Github: This is optional - you can choose yes if you want, but it would require extra configuration.
- Overwrite index.html: Choose no since we already have an existing
index.html
file.
After you initialized your firebase app, deploy your application to Firebase Hosting by running:
firebase deploy
This command will upload your files to Firebase and provide you with a hosting URL where your website is live. After deployment, the Firebase CLI will output a hosting URL (e.g., https://your-project-id.web.app
). Open this URL in your browser to see your live website.
Demo website: https://fireship-test-d3523.web.app.
Full code: https://github.com/CometBlazer/simple-firebase-login.
Conclusion
You've successfully created a simple login system using Firebase, HTML, and CSS. This setup can be expanded with additional features such as password reset, email verification, and integrating with other Firebase services. Firebase makes it easy to add robust authentication to your web applications, allowing you to focus on building your app's core functionality.
Happy coding! 🚀