Bird
Raised Fist0
Firebasecloud~10 mins

User session management in Firebase - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - User session management
User logs in
↓
Firebase creates session token
↓
Token stored on client
↓
User makes requests
↓
Firebase verifies token
↓
If token valid
→Allow access
No↓
Request denied, ask login
This flow shows how Firebase manages user sessions by creating a token at login, storing it on the client, verifying it on requests, and allowing or denying access.
Execution Sample
Firebase
firebase.auth().signInWithEmailAndPassword(email, password)
  .then(userCredential => {
    const user = userCredential.user;
    return user.getIdToken();
  })
  .then(token => {
    // Store token for session
  });
This code logs in a user with email and password, then gets a session token to manage the user session.
Process Table
StepActionFirebase ResponseClient StateNext Step
1User submits login formReceives login requestNo session tokenVerify credentials
2Firebase verifies credentialsCredentials validNo session tokenCreate session token
3Firebase creates session tokenToken generatedNo session tokenSend token to client
4Client receives tokenToken sentStores token locallyUser authenticated
5User makes authenticated requestReceives request with tokenHas tokenVerify token validity
6Firebase verifies tokenToken validHas tokenAllow access to resource
7User makes request with expired tokenReceives request with tokenHas expired tokenReject request, ask login
8User logs outSession endedToken removed from clientUser unauthenticated
💡 Execution stops when user logs out or token expires and user must log in again.
Status Tracker
VariableStartAfter Step 3After Step 4After Step 6After Step 8
sessionTokennullnulltoken123abctoken123abcnull
userAuthenticatedfalsefalsetruetruefalse
Key Moments - 3 Insights
Why does the client store the session token after login?
The client stores the token (see execution_table step 4) so it can send it with future requests to prove the user is logged in.
What happens if the token expires before the user logs out?
At step 7, Firebase rejects requests with expired tokens, forcing the user to log in again to get a new token.
Does logging out immediately remove the token from Firebase?
No, logging out removes the token from the client (step 8), ending the session from the user's side.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the client state after step 4?
ANo session token stored
BUser unauthenticated
CSession token stored locally
DToken expired
💡 Hint
Check the 'Client State' column at step 4 in the execution_table.
At which step does Firebase verify the token validity?
AStep 4
BStep 6
CStep 2
DStep 8
💡 Hint
Look for 'Firebase verifies token' in the 'Action' column of the execution_table.
If the user logs out, what happens to the sessionToken variable according to variable_tracker?
AIt becomes null
BIt changes to a new token
CIt remains the same
DIt becomes expired
💡 Hint
Check the 'sessionToken' row in variable_tracker after step 8.
Concept Snapshot
User session management in Firebase:
- User logs in with credentials
- Firebase creates a session token
- Token stored on client for future requests
- Firebase verifies token on each request
- Expired tokens cause access denial
- Logging out removes token from client
Full Transcript
User session management in Firebase starts when the user logs in with their email and password. Firebase checks the credentials and creates a session token if valid. This token is sent to the client and stored locally. When the user makes requests, the client sends the token to Firebase, which verifies it. If the token is valid, access is allowed. If the token expires or the user logs out, the session ends and the user must log in again to get a new token.

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

  1. Step 1: Understand user session management

    User session management is about tracking user login status and keeping users logged in securely.
  2. Step 2: Identify the correct purpose in Firebase context

    Firebase Auth provides methods to manage user sessions, ensuring users stay logged in safely.
  3. Final Answer:

    To keep track of who is logged in and maintain their login state safely -> Option A
  4. 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

  1. Step 1: Recall Firebase Auth sign-out method

    The correct method to sign out a user in Firebase Auth is signOut().
  2. Step 2: Verify method names

    Other options like signIn(), logOut(), and endSession() are incorrect or do not exist in Firebase Auth.
  3. Final Answer:

    firebase.auth().signOut() -> Option A
  4. 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

  1. Step 1: Understand onAuthStateChanged behavior

    This method listens for changes in user authentication state and calls the callback with the user object or null.
  2. Step 2: Analyze the callback logic

    If user exists (logged in), it logs 'User is signed in'; otherwise, it logs 'No user signed in'.
  3. Final Answer:

    Logs 'User is signed in' if a user is logged in, else 'No user signed in' -> Option B
  4. 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:
firebase.auth().setPersistence('LOCAL')
  .then(() => {
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch(error => {
    console.error(error);
  });
medium
A. 'LOCAL' is not a valid persistence type
B. setPersistence must be called after signInWithEmailAndPassword
C. setPersistence should use firebase.auth.Auth.Persistence.LOCAL constant
D. Missing await keyword before setPersistence

Solution

  1. Step 1: Check setPersistence argument

    Firebase expects persistence constants like firebase.auth.Auth.Persistence.LOCAL, not string 'LOCAL'.
  2. Step 2: Confirm correct usage

    Using the constant ensures valid persistence setting; strings cause errors.
  3. Final Answer:

    setPersistence should use firebase.auth.Auth.Persistence.LOCAL constant -> Option C
  4. 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

  1. 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.
  2. Step 2: Match requirement to persistence

    To keep users signed in only during the browser session, SESSION persistence is correct.
  3. Final Answer:

    firebase.auth.Auth.Persistence.SESSION -> Option D
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard