Auth Overview
client SDK: user authentication
The client-SDK provides workflows to authenticate the user against Firebase's authentication servers.
auth object
We store a reference to the auth object for use in various functions auth-related functions or to access currentUser . It is initialized with a given app object.
const auth = getAuth(app)
auth.currentUser // User | null
currentUser starts as null. When the SDK has finished initializing, it becomes the user object if the user has been logged-in automatically. Otherwise it stays null. It's also null when the user logs out.
User instance properties
uid uniquely identifies the user. Other properties are optional.
uid
email
phoneNumber
displayName
isAnonymous
listen to authentication state changes
We may listen to authentication events and update the app accordingly. Technically, we provide a callback to onAuthStateChanged, which is run by Firebase on auth event, and given a user object.
The state changes when:
-
the user registers (sign-up)
-
the user logs in (sign-in)
-
the user logs out (sign-out)
the login may occur in two ways:
- the user fills the login form and submits it successfully
- the user is recognized by the SDK and is logged in automatically
onAuthStateChanged(auth, (user) => {
const isAuthenticated = Boolean(user)
// setIsAuthenticated(isAuthenticated)
// setIsLoading(false)
// const userID = user.uid
})
React patterns
We store the authentication status (logged-in or not) in a state variable such as isAuthenticated.
We display the authenticated area when isAuthenticated is true.
At page launch, the authentication state is not determined.
We may add a second state variable to keep track of the loading state, such as isLoading. It starts as true and switches to false on the first authentication event.
// loading
isLoading // true
isAuthenticated // false
// loaded
isLoading // false
isAuthenticated // true or false
automatic login after registration
If the registration succeeds, the user is automatically logged-in. We may detect the change by listening to auth.currentUser. The user remains logged-in in a given browser until a manual logout.
others
sign-out works for any auth provider:
signOut(auth)