Search⌘ K
AI Features

Making Your App Aware of Users

Explore how to make your Firebase app aware of users by using the onAuthStateChanged method. Learn to monitor authentication status in real time, control UI elements based on sign-in or sign-out state, and dynamically display user information in your app's header.

With any Firebase application, we need to add our configuration details to the top of our JavaScript file. For this app, we will also make a variable for auth so that we can access them easily throughout the app.

Javascript (babel-node)
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "provided apiKey",
authDomain: "provided authDomain",
databaseURL: "provided databaseURL",
projectId: "provided projectId",
storageBucket: "provided storageBucket",
messagingSenderId: "provided messagingSenderId",
appId: "provided appId"
}
// Initialize Firebase
firebase.initializeApp(firebaseConfig)
// Reference to auth method of Firebase
const auth = firebase.auth()

Invoke onAuthStateChanged Firebase Method #

Making your app aware of the user’s authentication state is as easy as invoking the onAuthStateChanged Firebase method. It makes displaying different things to your users based on their state incredibly easy.

Firebase monitors the auth state in real-time. We can use an if/else statement to do different things based on that state.

Javascript (babel-node)
// declare uid globally so you can access it throughout your app
let uid
auth.onAuthStateChanged(user => {
if (user) {
// Everything inside here happens if user is signed in
console.log(user)
// this assigns a value to the variable 'uid'
uid = user.uid
modal.style.display = `none`
} else {
// Everything inside here happens if user is not signed in
console.log('not signed in')
}
})

Check Your Console

...