Auth
interact with authentication servers from the client
Google manages the authentication servers. As developers we focus on interacting with those servers from the client. We use the Auth client SDK.
auth object
We get and keep a reference to the auth object as we use it in various methods and because it holds currentUser
. We give it ``app` so that it receives the config.
const auth = getAuth(app)
currentUser starts as null. When the SDK has finished initializing, it switches to an object if a user has been logged-in automatically. Otherwise it stays null. It's also null when the user logs out.
auth.currentUser // User | null
User type
uid uniquely identifies the user. Other properties are optional.
uid
email
phoneNumber
displayName
request registration, and other requests related to Auth
attempt to register
createUserWithEmailAndPassword(auth, email, password)
attempt to sign-in
signInWithEmailAndPassword(auth, email, password)
sign-out
signOut(auth)
ask for a password reset mail
sendPasswordResetEmail(auth, email)
patterns to manage failed attempts
await within try...catch
async function signUp() {
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password)
console.log("user ID:", userCredential.user.uid)
} catch (error) {
console.log(error)
} finally {
setIsLoading(false)
}
}
trailing then...catch
createUserWithEmailAndPassword(auth, email, password)
.catch((error) => alert(error.message))
.finally(() => setIsLoading(false))
react to authentication state changes
We call onAuthStateChanged
to register a callback. Each time firebase runs our callback, it provides us with the 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
In React apps, we store the user authentication status 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 keep track of it in a isLoading
state variable. It would default to true and switch to false on the first authentication event.
// loading
isLoading // true
isAuthenticated // false
// loaded
isLoading // false
isAuthenticated // true or false