Managing User Sessions & States
Learn how to monitor user authentication states, persist sessions, and manage user profiles securely.
Managing User Sessions & States is a free Firebase Auth & Realtime Database Apps lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Firebase Auth & Realtime Database Apps learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
User Sessions & States Intro
Welcome! In this lesson, we'll dive into managing user sessions and understanding authentication states in Firebase. These are crucial for building secure and user-friendly apps.
We'll cover how to:
- Monitor when a user logs in or out.
- Keep users logged in across app restarts.
- Update user profile information.
Tracking User Status
Firebase Authentication provides a powerful way to monitor a user's login status in real-time. This is done using an "authentication state listener."
- It tells your app if a user is currently logged in or logged out.
- It fires whenever the user's authentication state changes (e.g., login, logout, token refresh).
- This is perfect for updating UI elements or redirecting users.
Live Auth State Listener
Here's how you set up an authentication state listener. It's a key part of making your app react to user logins and logouts.
This example assumes Firebase is initialized and the auth service is available.
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
// This function will be called whenever the auth state changes
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in
console.log("User logged in:", user.email);
// You can access user.uid, user.displayName, etc.
} else {
// User is signed out
console.log("No user logged in.");
}
});
console.log("Auth state listener set up.");Session Persistence Explained
Imagine your user logs in, closes the app, and reopens it only to find they're logged out. Frustrating, right?
Firebase Auth solves this with "session persistence." It allows you to specify how long a user's login session should last, even after they close their browser or app.
- Firebase stores user credentials securely.
- It automatically re-authenticates the user when they return.
Choosing Persistence Options
Firebase offers different levels of session persistence to suit various application needs:
LOCAL: The user's session is persisted even if the browser window is closed. (Default for web)SESSION: The session is persisted only for the current browser session. It's cleared when the window is closed.NONE: No session persistence. The user is logged out when the page is refreshed or the app restarts.
Customizing Session Persistence
You can set the desired persistence level before a user signs in. This tells Firebase how to handle the session for that specific login.
Here's an example of setting it to SESSION for a temporary login.
import { getAuth, setPersistence, browserSessionPersistence } from "firebase/auth";
const auth = getAuth();
// Set persistence to SESSION
setPersistence(auth, browserSessionPersistence)
.then(() => {
console.log("Persistence set to SESSION.");
// Now you can sign in your user
// signInWithEmailAndPassword(auth, email, password);
})
.catch((error) => {
console.error("Error setting persistence:", error.message);
});
console.log("Attempting to set persistence...");Accessing User Info
Once a user is logged in, you often need to access their information like their ID, email, or display name. Firebase makes this easy.
- The
currentUserproperty of theauthobject holds the currently logged-in user. - It will be
nullif no user is logged in. - Important: Always check
currentUserinside anonAuthStateChangedlistener to ensure it's up-to-date.
Managing User Profiles
Firebase Auth allows users to update basic profile information directly. This includes their display name and profile photo URL.
These updates are client-side and don't require re-authentication for the user to see the changes in their own profile object.
- Use the
updateProfilemethod on the user object. - Common updates:
displayNameandphotoURL.
Changing Display Name
Let's see how to update a user's display name. This is useful for personalizing their experience in your app.
This operation requires a logged-in user.
import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
const user = auth.currentUser; // Get the current user
if (user) {
updateProfile(user, {
displayName: "Jane Doe",
// photoURL: "https://example.com/jane-profile.jpg"
}).then(() => {
console.log("Profile updated successfully!");
console.log("New display name:", user.displayName);
}).catch((error) => {
console.error("Error updating profile:", error.message);
});
} else {
console.log("No user is logged in to update profile.");
}
console.log("Attempting to update user profile...");Quick Check: Auth State
Consider a web application using Firebase Authentication. A user logs in, then closes their browser and reopens it a few minutes later. They find themselves still logged in.
Which Firebase Auth persistence setting was most likely active?
Recap: Sessions & States
Great job! In this lesson, you learned how to effectively manage user sessions and states in your Firebase application.
- We explored
onAuthStateChangedfor real-time user status monitoring. - You understood the importance of session persistence and its different levels (
LOCAL,SESSION,NONE). - Finally, you learned how to access and update a logged-in user's profile information.
These skills are fundamental for building dynamic and personalized user experiences!
Frequently asked questions
Is the “Managing User Sessions & States” lesson free?
Yes — the full text of “Managing User Sessions & States” is free to read here on the web, and the Firebase Auth & Realtime Database Apps course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Firebase Auth & Realtime Database Apps course, upgrade to CoddyKit PRO.
What will I learn in “Managing User Sessions & States”?
Learn how to monitor user authentication states, persist sessions, and manage user profiles securely. You practise Firebase Auth & Realtime Database Apps with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Firebase Auth & Realtime Database Apps?
No prior experience is required. Firebase Auth & Realtime Database Apps on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Managing User Sessions & States” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Firebase Auth & Realtime Database Apps lesson?
Yes. Every Firebase Auth & Realtime Database Apps lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Email/Password Authentication Implementation
- Managing User Sessions & States
- Handling Authentication Errors
- Password Reset & Email Verification