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

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
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:
</>) in the project overview.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.
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.
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:
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.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.