How to add firebase authentication(with email and password) in your React app
In this article, we are going to cover firebase authentication step-by-step:
Prerequisites:
- Basic Knowledge of React.
- Basic working of firebase.
1. Let's install firebase in our console
npm install firebase
2. Now to set up the firebase to your app follow this code
Note: The firebaseConfig
can get from firebase when you create your app.
Now that we have firebase in our app let's enable the authentication method in firebase
3. To enable the authentication method, follow this path
firebase.google.com -> go to console -> choose the project you want to add authentication to -> go to authentication -> enable sign-in method as Email/password
4. Now we are going to set the user in our app so that we can use it anywhere
We use the useEffect
hook here so that any time the user auth state change onAuthStateChanged()
method will run.
Note: onAuthStateChanged()
is provided by firebase auth.
5. Create a new user: 👨💻
const signup = (event) => {
event.preventDefault();
auth.createUserWithEmailAndPassword(email, password)
.then((authUser) => {
return authUser.user.updateProfile({
displayName: username
})
})
.catch(error => console.log(error))
}
displayName
is the property in the user object. We want displayName
to update with the username user provided us during signup.
6. Sign in a user ⬅️
When a user sign-in to your app, pass the user's email address and password to signInWithEmailAndPassword
:
const signin = (event) => {
event.preventDefault();
auth.signInWithEmailAndPassword(email, password)
.catch(error => console.log(error))
}
7. To sign out a user ➡️
We created a button here to signOut
the user.
<button onClick={() => auth.signOut()}>logout</button>
It's very easy to sign out the user, you just need to call auth.signOut()
method provided by firebase auth.
And with that, you are ready to add authentication in your react app.🤩
That's it for this article!