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.
We'll cover the following...
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 configurationvar firebaseConfig = {apiKey: "provided apiKey",authDomain: "provided authDomain",databaseURL: "provided databaseURL",projectId: "provided projectId",storageBucket: "provided storageBucket",messagingSenderId: "provided messagingSenderId",appId: "provided appId"}// Initialize Firebasefirebase.initializeApp(firebaseConfig)// Reference to auth method of Firebaseconst 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 applet uidauth.onAuthStateChanged(user => {if (user) {// Everything inside here happens if user is signed inconsole.log(user)// this assigns a value to the variable 'uid'uid = user.uidmodal.style.display = `none`} else {// Everything inside here happens if user is not signed inconsole.log('not signed in')}})