Open In App

How to Get Currently Signed In User in Web and Firebase ?

Improve
Improve
Like Article
Like
Save
Share
Report

Firebase is the most widely used Database and it has awesome features such as Authentication firestore, and Real-time database, given by firebase, We can integrate firebase into Web, Flutter, and Unity. But In this article, we are going to implement firebase on the web and get the current Signed In user.

A sample below give an idea of what we are going to implement:

 

Create a User using firebase Authentication: You create a new user in your Firebase project by calling the createUserWithEmailAndPassword method or by signing in a user for the first time using a federated identity provider, such as Google Sign-In or Facebook Login.

You can also create new password-authenticated users from the Authentication section of the Firebase console, You can follow this GFG article to implement the firebase on the web and User Authentication using Email and Password.

Hopefully, now you read the mentioned article, And now we are going to get the user signed in the state in firebase and web.

Get the currently signed-in user: The recommended way to get the current user is by setting an observer on the Auth object:

Javascript




firebase.auth().onAuthStateChanged((user) => {
    if (user) {
  
        // User is signed in
        console.log("User Signed In");
        var uid = user.uid;
        // ...
    } else {
        // User is signed out
        console.log("User Signed Out");
        // ...
    }
});


Alternative way: You can also get the currently signed-in user by using the currentUser property. If a user isn’t signed in, currentUser is null:

Javascript




const user = firebase.auth().currentUser;
  
if (user) {
  
    // User Signed In
    console.log("User Signed In");
    // ...
} else {
    // No user is signed in.
    console.log("User Signed Out");
}


Note: currentUser might also be null because the auth object has not finished initializing. You can handle this using observer.

Example: Below is the implementation to Get the currently Signed In user in web and Firebase:

  • index.html: We have only three buttons in the body of the HTML file that calls the method signin, sign out and check respectively. The definition of above methods is defined in the JavaScript file. 

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
          content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>samplefirebaseforweb</title>
    <script src=
      </script>
</head>
<body>
    <script src="/app.js"></script>
    <button onclick="signIn()">signUp</button>
    <button onclick="signOut()">signOut</button>
    <button onclick="Check()">Check SignIn or Not</button>
</body>
</html>


script.js: JavaScript file that adds the firebase to the web app and methods that are used to signed in the user,  sign out the user, and check whether the user is signed in or not.

Javascript




const firebaseConfig = {
    // Your firebase configuration detail come here 
};
  
// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
  
var email = "xyz12@gmail.com"; // Arbitrary email
var password = "12345678";
  
// Method to sign in the user
function signIn() {
    firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .then((userCredential) => {
            // Signed in
            var user = userCredential.user;
  
            // ...
        })
        .catch((error) => {
            var errorCode = error.code;
            var errorMessage = error.message;
        });
}
  
// Method to sign out the user
function signOut() {
    firebase
        .auth()
        .signOut()
        .then(() => {
            // Sign-out successful.
        })
        .catch((error) => {
            // An error happened.
        });
}
  
// Check the user sign in or not
function Check() {
    firebase.auth().onAuthStateChanged((user) => {
        if (user) {
            // User Signed In
            console.log("User Signed In!!");
        } else {
            // User is signed out
            console.log("User Signed out!!");
            // ...
        }
    });
}


Output:

 



Last Updated : 31 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads