Most apps these days require creation of a user to login and logout for access to the tools that they offer. Let's go over the basics of implementing these functionalities through Firebase Authentication with a user's email and password!
Setting Up
First, let's grab the Firebase SDK snippet from our project's settings in the Firebase Console, and paste it into the bottom of our main index.html
file's <body>
tag so that we can use the Firebase functions in our app. We will also add a script tag specifically for Firebase Authentication, and call firebase.auth()
set it to a const
variable auth
for its service interface.
And, of course, let's remember to also include the script for the main index.js
file.
All together, it should look something like this:
<html>
<header></header>
<body>
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js"></script>
<!-- Below is the additional script for Firebase Auth -->
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-auth.js"></script>
<script>
var firebaseConfig = {
apiKey: "AIzaSyDP5OCeuEQD3IJXI252-fa3atPKhPaxPOl",
authDomain: "your-project-name.firebaseapp.com",
databaseURL: "https://your-project-name.firebaseio.com",
projectId: "your-project-name"
};
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
</script>
<script src="scripts/index.js"></script>
</body>
</html>
Now let's make a basic form with input fields for email
and password
, as well as buttons for Sign Up
, Login
and Logout
that will go inside the <body>
of our index.html
file above the script tags:
<form>
<input type="email" id="email" />
<label for="email">Email</label>
<br>
<input type="password" id="password" />
<label for="password">Password</label>
<br>
<button id="signup-btn">Sign Up</button>
<button id="login-btn">Login</button>
<button id="logout-btn">Logout</button>
</form>
Great! Now let's add an index.js
file in the same directory and start building the functions.
Sign Up
Since we have a Sign Up
button, we will start off by querying it by the button's ID (in this case it is "signup-btn"
) and store this in a variable signupBtn
. Upon a click event on this DOM element, we'll next want to grab the password
and email
values, and save them into variables to pass into the Firebase function createUserWithEmailAndPassword
. This is an asynchronous operation that returns a Promise, so let's tag on a .then()
, which takes a callback function (for our purposes, it will be cred
for "credentials"), and let us know in the browser console that the user has signed up.
const signupBtn = document.querySelector('#signup-btn');
signupBtn.addEventListener('click', e => {
e.preventDefault();
const email = document.querySelector('#email').value;
const password = document.querySelector('#password').value;
auth.createUserWithEmailAndPassword(email, password).then(cred => {
console.log('User signed up!');
});
});
Let's test it out now in the browser. After entering an email and password and clicking the Sign Up
button, let's navigate over to our Firebase Console and refresh it to see the new user that has been added:
It works! You'll notice that Firebase also automatically generates a UID for the user as well.
Login
We'll now set up our login function and add an event listener on that Login
button. It's going to look pretty similar to what we've done with the sign-up function above, but the main difference here is the Firebase function we'll be using to sign in, which is signInWithEmailAndPassword
. This also returns a Promise, so we'll add a .then
to log in the browser console a little message if we successfully sign in, and a .catch
to show an error message if we don't.
const loginBtn = document.querySelector('#login-btn');
loginBtn.addEventListener('click', e => {
e.preventDefault();
const email = document.querySelector('#email').value;
const password = document.querySelector('#password').value;
auth.signInWithEmailAndPassword(email, password)
.then(cred => {
console.log('Logged in user!');
})
.catch(error => {
console.log(error.message);
})
});
Logout
This will be the quickest function to build, as all we need to call here is Firebase's signOut
function. Again, we'll use the browser console to just make sure this is working.
const logoutBtn = document.querySelector('#logout-btn');
logoutBtn.addEventListener('click', e => {
e.preventDefault();
auth.signOut();
console.log('User signed out!');
})
Keeping Track of Auth State
With the above three functions, a user can now sign up, login and logout of our app, but we also need to keep track of the sign-in state of the user in order to determine when to show certain data. To do this, we will use Firebase's onAuthStateChanged
method, which returns either the signed in Firebase user, or null
if not signed in. When calling this function, we'll first check to see if the user exists, and if so then put in the console that they are logged in. Let's reference the user by user.email
so that we will see their actual email address; else, when the user is not signed in, we will simply log a message indicating that the user is logged out.
auth.onAuthStateChanged(user => {
if (user) {
console.log(user.email + " is logged in!");
} else {
console.log('User is logged out!');
}
});
Once we've got these working, we can then put additional functionalities to read data only when the user is logged in, show a signup page when logged out, etc.
Helpful Link
🔥 The Net Ninja's Firebase Auth Tutorial 🔥
I cannot say enough how helpful I found these tutorial videos. The Net Ninja is amazing at breaking down concepts into short videos at a time, and I had such a great time following along because his explanations are easy to understand. I would highly recommend checking it out!
Top comments (0)