...

/

Making Your App Aware of Users

Making Your App Aware of Users

This lesson covers a powerful feature of the ​Firebase - the authentication state. With a tiny bit of code, your application will be aware of signed in users.

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.

Press + to interact
// 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.

Press + to interact
// 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

...