Awonke Mnotoza

Site Owner

Connecting Firebase with Vanilla JavaScript

25 Jul 2023

0
share

What is Firebase?

Before we begin, we need to understand what is firebase and why you need it.

Firebase is a cloud computing service, provided by Google, that offers backend services like authentication, database, etc.

It has an easy app integration as well as documentation to guide you on your development journey.

You will need to have a Google account to continue from here

Let us get started with Firebase

First, we need to create an account with Firebase.

Then we can create a project and continue from there.

Click on the link below to create an account with Firebase because you will need it in order to follow along.

Creating a project

Image

Click on the "Add Project"

Then enter your project name and continue

Image

Disable the google analytics because we will not be needing it, then click on "create project".

You will be greeted with your own dashboard.

Image

We need to create a web application so that we can connect it with our front-end application.

On the dashboard page, click on the web icon "<>" to create the web app on Firebase.

Image

Then enter the name of the app. Do not click on the Firebase hosting because we will not need it.

Scroll down and click on the button to go back to the dashboard.

Authentication project

We are going to create an authentication project, that will enable our users to signup with Google authentication.

But first, we need to set up authentication on the Firebase.

Image

On the sidebar, click on the "build" tab, then click on the "authentication" button.

Then click on the "Get Started" button.

Image

Choose the Google provider as we will only be using that.

Image

Enable the provider and select the email that you will be using.

Then click on save.

You can always add more providers later but for the purpose of this project, we will be focusing on the Google provider since it is easier to configure.

If you click on the users, you will see that it is empty.

We are done for now with Firebase, let us start coding

Coding the project

Create an empty folder and open it with your preferred IDE.

Create an HTML file, a CSS file, and a JavaScript file, and name them whatever you want.

I will be pasting the code here although I will be leaving the GitHub link below the blog

The HTML

Here I used Google font "Roboto".

I imported my JavaScript (make sure you defer your JavaScript and specify the type module since we will be using import-export) and CSS

I also used an SVG for the Google Logo

Contawo: html

Copy

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./index.css">
    <title>Firebase Connect</title>
    <script src="./index.js" type="module" defer></script>
</head>
<body>
    <!-- Will be shown when the user is unauthenticated -- >
    <button class="container">
        <div class="container-logo">
            <svg width="100%" height="100%" viewBox="0 0 25 26" fill="none" xmlns="http://www.w3.org/2000/svg">
               <path d="M24.9998 13.1935C24.9998 12.3441 24.9253 11.5376 24.7976 10.7527H12.7712V15.6021H19.6571C19.3485 17.1935 18.4439 18.5376 17.1029 19.4516V22.6774H21.211C23.6163 20.4301 24.9998 17.1183 24.9998 13.1935Z" fill="#4285F4"/>
                <path d="M12.7713 25.8064C16.2195 25.8064 19.1038 24.6452 21.211 22.6774L17.1029 19.4516C15.9535 20.2258 14.4954 20.6989 12.7713 20.6989C9.44007 20.6989 6.61972 18.4301 5.60865 15.3656H1.3728V18.6882C3.46944 22.9032 7.77978 25.8064 12.7713 25.8064Z" fill="#34A853"/>
                <path d="M5.60877 15.3656C5.3427 14.5914 5.20434 13.7634 5.20434 12.9032C5.20434 12.043 5.35334 11.215 5.60877 10.4409V7.11827H1.37292C0.500213 8.86021 0 10.8172 0 12.9032C0 14.9892 0.500213 16.9462 1.37292 18.6882L5.60877 15.3656Z" fill="#FBBC05"/>
                <path d="M12.7713 5.10753C14.6551 5.10753 16.3366 5.76344 17.667 7.04301L21.3068 3.36559C19.1038 1.27957 16.2195 0 12.7713 0C7.77979 0 3.46944 2.90323 1.3728 7.11828L5.60865 10.4409C6.61972 7.37634 9.44007 5.10753 12.7713 5.10753Z" fill="#EA4335"/>
           </svg>
        </div>
        <p class="container-text">Continue with Google</p>
    </button>
    <!-- Will be displayed when the user has been successfuly authenticated -->
    <section class="connected">
        <h1 class="connected-title">Connected</h1>
        <button class="connected-button">Logout</button>
    </section>
</body>
</html>

The CSS

I will not explain the styling because it is straightforward.

Contawo: css

Copy

:root {    
    --orange: #fd8045;    
    --orange-dark: #f85910;
}

* {    
    margin: 0;    
    padding: 0;    
    box-sizing: border-box;    
    font-family: 'Roboto', sans-serif;
}

body {    
    height: 100dvh;    
    width: 100dvw;    
    display: flex;    
    flex-direction: column;    
    align-items: center;    
    justify-content: center;    
    background: linear-gradient(23deg, rgba(255,152,103,1) 0%, rgba(255,255,255,1) 100%);
}

.container {    
    display: flex;    
    align-items: center;    
    padding: 1rem 2rem;    
    border-radius: 10px;    
    border: none;    
    outline: none;    
    gap: 1rem;    
    background: var(--orange);    
    color: white;    
    cursor: pointer;    
    transition: .3s all linear;
}

.container:hover {    
    background-color: var(--orange-dark);
}

.container-logo {    
    height: 1.5rem;    
    width: 1.5rem;
}

.connected {    
    display: flex;    
    flex-direction: column;    
    gap: 1rem;    
    align-items: center;
}

.connected-title {    
    font-size: 4rem;
}

.connected-button {    
    padding: 1rem 2rem;    
    border-radius: 5px;    
    background-color: var(--orange);    
    color: white;    
    border: none;    
    outline: none;    
    cursor: pointer;    
    transition: .3s all linear;
}

.connected-button:hover {    
    background-color: var(--orange-dark);
}

The JavaScript

Here we need to go back to our firebase to collect some information that will enable us to connect with firebase.

Image

Navigate to the project settings.

Image

Scroll down till you get to the bottom part where you will see the code.

Make sure that the checkbox is on the CDN, not npm.

Copy the code inside the script tags and paste it into your JavaScript File.

Contawo: javascript

Copy

// Import the functions you need from the SDKs you needimport { initializeApp } from "https://www.gstatic.com/firebasejs/10.1.0/firebase-app.js";

import { getAuth, GoogleAuthProvider, signInWithPopup, signOut } from "https://www.gstatic.com/firebasejs/10.1.0/firebase-auth.js";

const firebaseConfig = {  
    apiKey: "AIzaSyArgrQQIB65MdcsqDnZE8Vs-POBy5OwaUY",  
    authDomain: "fir-connect-5dd25.firebaseapp.com",  
    projectId: "fir-connect-5dd25",  
    storageBucket: "fir-connect-5dd25.appspot.com",  
    messagingSenderId: "426090292848",  
    appId: "1:426090292848:web:e42f1f4cdd580882a5b6b5"
};

// Initialize Firebaseconst app = initializeApp(firebaseConfig);
const auth = getAuth(app)

const googleButton = document.querySelector(".container");
const connectedContainer = document.querySelector(".
const logoutButton = document.querySelector(".connected-button");

connectedContainer.style.display = "none";
googleButton.addEventListener("click", () => {
    const provider = new GoogleAuthProvider();
    signInWithPopup(auth, provider).then(() => {
        alert("Signed in successfully")
        googleButton.style.display = "none";
        connectedContainer.style.display = "flex";
    }).catch((err) => {
        alert("Signed in unsuccessfully")
        googleButton.style.display = "flex";
        connectedContainer.style.display = "none";
    })})

logoutButton.addEventListener("click", () => {
    signOut(auth).then(() => {
        alert("Signout successfully")
        connectedContainer.style.display = "none";
        googleButton.style.display = "flex";
    }).catch(() => {
        alert("Failed to logout")
        connectedContainer.style.display = "flex";
        googleButton.style.display = "none";
    })})
Please ensure that you do not use the same credentials I have used, use yours.

We have reached the end of our blog, if you have any questions that you would like to ask, please leave a comment. If there is anything that I have missed, please let me know in the comments as well, I would love to hear from you.

Learn more about JavaScript and the Web

If you are curious like me and want to learn more about JavaScript and the Web.

Also get a certificate of completion, so that you can start applying for jobs.

Start learning today by clicking the link below.

Please comment on your thoughts and any questions you have.

Comments

Be the first to comment...