How to Get Current User in Firebase: Simple Guide
To get the current user in Firebase, use
firebase.auth().currentUser in JavaScript or the equivalent method in your platform's SDK. This returns the user object if someone is signed in, or null if no user is signed in.Syntax
The main way to get the current user in Firebase Authentication is by accessing the currentUser property from the Firebase Auth instance.
firebase.auth(): Gets the Firebase Authentication service instance.currentUser: Property that holds the currently signed-in user ornullif no user is signed in.
javascript
const user = firebase.auth().currentUser;Output
user is an object if signed in, otherwise null
Example
This example shows how to check if a user is signed in and then access their unique ID and email.
javascript
import { initializeApp } from 'firebase/app'; import { getAuth, onAuthStateChanged } from 'firebase/auth'; const firebaseConfig = { apiKey: 'YOUR_API_KEY', authDomain: 'YOUR_AUTH_DOMAIN', projectId: 'YOUR_PROJECT_ID', }; const app = initializeApp(firebaseConfig); const auth = getAuth(app); onAuthStateChanged(auth, (user) => { if (user) { console.log('User ID:', user.uid); console.log('User Email:', user.email); } else { console.log('No user is signed in.'); } });
Output
User ID: abc123xyz
User Email: user@example.com
// or
No user is signed in.
Common Pitfalls
Many developers try to get the current user immediately after page load without waiting for Firebase to initialize the auth state, which returns null even if a user is signed in.
Always use onAuthStateChanged listener to get the current user reliably.
javascript
/* Wrong way: May return null if auth state not ready */ const user = firebase.auth().currentUser; console.log(user); // null even if signed in /* Right way: Use listener to wait for auth state */ firebase.auth().onAuthStateChanged(user => { if (user) { console.log('User is signed in:', user.uid); } else { console.log('No user signed in'); } });
Output
null
// or
User is signed in: abc123xyz
Quick Reference
Remember these key points when getting the current user in Firebase:
- Use
firebase.auth().currentUserto get the user object. - Use
onAuthStateChangedto listen for sign-in state changes. currentUserisnullif no user is signed in or auth state is not initialized.- User object contains useful info like
uid,email, anddisplayName.
Key Takeaways
Use firebase.auth().currentUser to get the current signed-in user object.
Always use onAuthStateChanged listener to reliably detect user sign-in state.
currentUser is null if no user is signed in or auth state is not yet ready.
User object includes uid, email, and other profile info.
Avoid accessing currentUser immediately on page load without waiting for auth state.