📖 Scenario: You are building a simple web app that needs to keep track of user sessions. Using Firebase Authentication, you will manage user login state to show personalized content.
🎯 Goal: Create a Firebase user session management setup that initializes Firebase, sets up a user state listener, and updates the UI based on whether the user is logged in or not.
📋 What You'll Learn
Initialize Firebase with a given config object
Create a function to listen for user authentication state changes
Update a variable userSession to hold the current user or null
Add a function to sign out the user
💡 Why This Matters
🌍 Real World
Managing user sessions is essential for any app that requires login. Firebase Authentication simplifies this by providing easy-to-use methods to track user state.
💼 Career
Understanding user session management with Firebase is valuable for frontend and backend developers working on web and mobile apps that require secure user authentication.
Progress0 / 4 steps
1
Initialize Firebase App
Create a constant called firebaseConfig with the exact keys and values: apiKey: 'AIzaSyA-1234567890abcdef', authDomain: 'your-app.firebaseapp.com', projectId: 'your-app', storageBucket: 'your-app.appspot.com', messagingSenderId: '1234567890', appId: '1:1234567890:web:abcdef123456'. Then initialize Firebase app by calling initializeApp(firebaseConfig) and assign it to a constant called app.
Firebase
Hint
Use const to create firebaseConfig object with the exact keys and values. Then call initializeApp(firebaseConfig) and assign it to app.
2
Set Up Authentication and User Session Variable
Import getAuth from Firebase and create a constant called auth by calling getAuth(app). Then create a variable called userSession and set it to null.
Firebase
Hint
Import getAuth from Firebase Auth module. Then create auth by calling getAuth(app). Initialize userSession as null.
3
Listen for User Authentication State Changes
Use auth.onAuthStateChanged with a callback function that takes a parameter user. Inside the callback, set userSession to user if it exists, otherwise set it to null.
Firebase
Hint
Use auth.onAuthStateChanged with a function that sets userSession to user if logged in, or null if not.
4
Add Sign Out Function
Create an async function called signOutUser that calls auth.signOut() to sign out the current user.
Firebase
Hint
Create an async function signOutUser that calls auth.signOut() to log out the user.
Practice
(1/5)
1. What is the main purpose of user session management in Firebase?
easy
A. To keep track of who is logged in and maintain their login state safely
B. To store user data permanently in the database
C. To manage server resources automatically
D. To create user interface themes dynamically
Solution
Step 1: Understand user session management
User session management is about tracking user login status and keeping users logged in securely.
Step 2: Identify the correct purpose in Firebase context
Firebase Auth provides methods to manage user sessions, ensuring users stay logged in safely.
Final Answer:
To keep track of who is logged in and maintain their login state safely -> Option A
Quick Check:
User session management = track and maintain login state [OK]
Hint: Remember: session management = tracking login state [OK]
Common Mistakes:
Confusing session management with data storage
Thinking it manages server resources
Mixing UI features with session handling
2. Which Firebase Auth method is used to sign out a user?
easy
A. firebase.auth().signOut()
B. firebase.auth().endSession()
C. firebase.auth().logOut()
D. firebase.auth().signIn()
Solution
Step 1: Recall Firebase Auth sign-out method
The correct method to sign out a user in Firebase Auth is signOut().
Step 2: Verify method names
Other options like signIn(), logOut(), and endSession() are incorrect or do not exist in Firebase Auth.
Final Answer:
firebase.auth().signOut() -> Option A
Quick Check:
Sign out method = signOut() [OK]
Hint: Sign out uses signOut(), not logOut or endSession [OK]
Common Mistakes:
Using signIn() instead of signOut()
Assuming logOut() or endSession() exist
Confusing signOut() with session ending
3. What will be the output of this code snippet?
firebase.auth().onAuthStateChanged(user => {
if (user) {
console.log('User is signed in');
} else {
console.log('No user signed in');
}
});
medium
A. Always logs 'User is signed in'
B. Logs 'User is signed in' if a user is logged in, else 'No user signed in'
C. Throws an error because of syntax
D. Logs nothing because the callback is never called
Solution
Step 1: Understand onAuthStateChanged behavior
This method listens for changes in user authentication state and calls the callback with the user object or null.
Step 2: Analyze the callback logic
If user exists (logged in), it logs 'User is signed in'; otherwise, it logs 'No user signed in'.
Final Answer:
Logs 'User is signed in' if a user is logged in, else 'No user signed in' -> Option B
Quick Check:
onAuthStateChanged logs based on user presence [OK]
Hint: onAuthStateChanged callback runs on login state changes [OK]
Common Mistakes:
Thinking it always logs 'User is signed in'
Expecting syntax errors in correct code
Assuming callback never runs
4. Identify the error in this Firebase session persistence code:
B. setPersistence must be called after signInWithEmailAndPassword
C. setPersistence should use firebase.auth.Auth.Persistence.LOCAL constant
D. Missing await keyword before setPersistence
Solution
Step 1: Check setPersistence argument
Firebase expects persistence constants like firebase.auth.Auth.Persistence.LOCAL, not string 'LOCAL'.
Step 2: Confirm correct usage
Using the constant ensures valid persistence setting; strings cause errors.
Final Answer:
setPersistence should use firebase.auth.Auth.Persistence.LOCAL constant -> Option C
Quick Check:
Use persistence constants, not strings [OK]
Hint: Use firebase.auth.Auth.Persistence constants, not strings [OK]
Common Mistakes:
Passing string instead of constant for persistence
Calling setPersistence after sign-in
Forgetting to handle promises
5. You want users to stay signed in only during the browser session (not after closing). Which persistence setting should you use in Firebase Auth?
hard
A. firebase.auth.Auth.Persistence.LOCAL
B. firebase.auth.Auth.Persistence.NONE
C. firebase.auth.Auth.Persistence.PERMANENT
D. firebase.auth.Auth.Persistence.SESSION
Solution
Step 1: Understand persistence options
LOCAL keeps users signed in across browser restarts, SESSION keeps them signed in only during the current tab session, NONE signs out immediately on page reload.
Step 2: Match requirement to persistence
To keep users signed in only during the browser session, SESSION persistence is correct.
Final Answer:
firebase.auth.Auth.Persistence.SESSION -> Option D
Quick Check:
Session persistence = sign-in lasts only during browser session [OK]
Hint: SESSION persistence limits login to current browser session [OK]
Common Mistakes:
Choosing LOCAL which persists beyond browser close
Selecting NONE which signs out immediately
Using non-existent PERMANENT option
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.