/firebase-tutorials

How to check if user is logged in with Firebase?

Discover how to set up Firebase, check user authentication using onAuthStateChanged, and implement login/logout functionality in your web app.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to check if user is logged in with Firebase?

 

Step 1: Set Up Firebase in Your Project

 

Before you can check if a user is logged in with Firebase, you need to set up Firebase in your project. Here’s how you can do it for a web application:

  • Go to the Firebase Console and create a new project.
  • Add a web app to your Firebase project by clicking on the web icon (</>) in the project overview.
  • Follow the instructions to register your app. It will provide you with a Firebase configuration object.

Include the Firebase SDK in your HTML file:

<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js"></script>

Initialize Firebase with your 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"
};

const app = firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();

 

Step 2: Check User Authentication State

 

To determine whether a user is logged in, you can use Firebase's onAuthStateChanged method, which sets an observer on the user's authentication state.

  • Add the following script to check if a user is signed in or not:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in
    const uid = user.uid;
    console.log('User is logged in with UID:', uid);
  } else {
    // User is signed out
    console.log('No user is logged in.');
  }
});

 

Step 3: Handling User Login

 

If you want to implement user login to test the state, add this snippet to handle authentication using email and password:

  • Ensure you've set up Firebase Authentication by going to the Firebase Console, selecting your project, and enabling Email/Password Authentication under "Sign-in Method."

  • Once Email/Password sign-in is enabled, you can proceed with the following code:


const email = "[email protected]";  // Replace with user's email
const password = "userpassword";   // Replace with user's password

firebase.auth().signInWithEmailAndPassword(email, password)
  .then((userCredential) => {
    // Successful login
    console.log('User successfully logged in:', userCredential.user);
  })
  .catch((error) => {
    // Handle authentication errors
    const errorCode = error.code;
    const errorMessage = error.message;
    console.error('Login Error:', errorCode, errorMessage);
  });

 

Step 4: Verify User Login on Page Load

 

To ensure the check for user authentication runs as soon as the page loads, wrap the onAuthStateChanged method inside an event listener for the window’s DOMContentLoaded event for better control.

  • Add the following snippet to execute the user authentication check when the page fully loads:

document.addEventListener('DOMContentLoaded', (event) => {
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      // User is signed in
      const uid = user.uid;
      console.log('User is logged in with UID:', uid);
    } else {
      // User is signed out
      console.log('No user is logged in.');
    }
  });
});

 

Step 5: Debugging and Logging Out

 

To assist with debugging or if you need to force a user to log out, you can add a logout function:

  • Implement a logout function and bind it to a button click event:

function logout() {
  firebase.auth().signOut()
    .then(() => {
      console.log('User successfully logged out.');
    })
    .catch((error) => {
      console.error('Logout Error:', error);
    });
}

// Optionally, bind this function to a button
document.getElementById('logoutBtn').addEventListener('click', logout);

This tutorial provides a step-by-step approach to checking if a user is logged in using Firebase. Ensure you replace placeholders and configure your Firebase project credentials correctly.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022