사용자 세션 및 상태 관리
사용자 인증 상태를 모니터링하고, 세션을 유지하며, 사용자 프로필을 안전하게 관리하는 방법을 학습합니다.
사용자 세션 및 상태 관리은(는) CoddyKit의 무료 Firebase Auth & Realtime Database Apps 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Firebase Auth & Realtime Database Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Firebase Auth & Realtime Database Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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!
AI 튜터와 함께 Firebase Auth & Realtime Database Apps을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 11
- 레슨
- 44
자주 묻는 질문
“사용자 세션 및 상태 관리” 강의는 무료인가요?
네 — “사용자 세션 및 상태 관리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Firebase Auth & Realtime Database Apps 강의 전체를 잠금 해제할 수 있습니다. Firebase Auth & Realtime Database Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“사용자 세션 및 상태 관리”에서 뭘 배우나요?
사용자 인증 상태를 모니터링하고, 세션을 유지하며, 사용자 프로필을 안전하게 관리하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Firebase Auth & Realtime Database Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Firebase Auth & Realtime Database Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Firebase Auth & Realtime Database Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“사용자 세션 및 상태 관리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Firebase Auth & Realtime Database Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Firebase Auth & Realtime Database Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 이메일/비밀번호 인증 구현
- 사용자 세션 및 상태 관리
- 인증 오류 처리
- 비밀번호 재설정 및 이메일 인증