What you'll learn
- Explain what Firebase Auth is and its ease-of-use and security benefits for adding user authentication to a React app
- Create a Firebase project in the Firebase console and initialize the Firebase config in a React application
- Build Login and Home pages in a new create-react-app project so users can sign in with email and password
- Sign users in with a single Firebase Auth function call and confirm the result in a test account
- Listen for Firebase auth state changes so the app reflects whether a user is logged in
- Redirect unauthenticated users by encapsulating route-protection logic in its own component instead of each page
Free 56-minute video lesson with a full transcript and knowledge checks. No account needed to watch.
Overview
Join Shaun Wassell as he walks you through the basics of Firebase Auth and how to add it to a React application.
Introduction
Firebase Auth makes it much easier to add user authentication to your React applications than implementing everything from scratch. In this video, we discuss the basic approach of this section.
What is Firebase Auth?
Firebase Auth is a user authentication service provided by Google. In this video, we discuss what Firebase and Firebase Auth are, as well as some of the main benefits they provide.
Knowledge Check
Which of the following is how much Firebase Auth costs per month?
Creating Pages
In order to add user authentication to a React app, we must create a Login page. In this video, we see how to create and display this page in a React app.
Knowledge Check
Which of the following attributes hides the characters inside a text input?
Redirecting Unauthenticated Users
Generally, we want unauthenticated and authenticated users to be able to access different pages. In this video, we see how to create special route components that encapsulate this logic for us.
Knowledge Check
The _____ component, exported from React-Router-DOM, automatically sends the user to another route when displayed.
Signing In With Firebase Auth
Firebase Auth provides a very convenient function that lets us log a user in with a single line of code. In this video, we see how to do this.
Knowledge Check
The ________ function logs in a user via Firebase auth.
Listening for Auth Changes
Firebase Auth provides a very convenient function that lets us listen for changes in a user's authencated state. In this video, we see how to use this function in a React app.
Knowledge Check
The ________ function creates a subscription for auth-related changes in React/Firebase Auth applications.
Conclusion
I hope this has been informative for you and I would like to thank you for consuming.
View Transcript
Introduction
0:06Hi, everyone, Shaun Wassell here. Probably one of the biggest questions I get asked by people who are already familiar with React and basic Full-Stack concepts is, how do I add user authentication to my applications in the quickest and most secure way possible? In other words, how do I add user authentication to my apps without all of that added complexity that generally comes along with it? Well, almost always, my response to that question is two words, Firebase Auth. Firebase Auth is a service provided by Google that makes it incredibly easy to add user authentication to your applications without having to manage any of the difficult stuff yourself.
0:45And that's what we're going to be taking a look at here today. We're going to be seeing the basics of Firebase Auth and how to add it to a React application in order to allow ourselves to let our users log in. And we're also going to be seeing how to create routes that will only allow certain users to see the pages they contain. So without further ado, let's jump right in and see what all this stuff is going to look like.
What is Firebase Auth?
0:01[MUSIC PLAYING] All right, so before we start seeing how to incorporate Firebase Auth into a React app and how it lets us actually add user authentication to an app, let's talk a little bit about what Firebase is in the first place. So think about Firebase as kind of a user-friendly wrapper around Google Cloud platform. If any of you have ever used GCP or Amazon Web Services or Azure or one of those other providers before, chances are you've found that it's actually quite difficult to set up an application and make sure that it's performant and ready to serve thousands, if not millions, of users.
0:46That's why those kind of certifications exist. Because there's a lot you have to learn in order to make a lot of that stuff work. So what Firebase is essentially a wrapper around GCP, as I said, that takes care of a lot of that for you. And it has a lot of different products that are available. It's got Firebase Auth, which is what we're going to be taking a look at here today. And it's also got other things like database providers, which is called Firestore. It's got a storage solution, which is called Cloud storage.
1:17There's a lot of other options for products that you can use on here. But right now, we're just going to be taking a look at Firebase Auth, which as you may have guessed, is Firebase's user authentication provider. So let's talk about some of the benefits of Firebase Auth. First of all, one of the main benefits of Firebase Auth is that it is free. And yes, this is probably just to get you hooked on Firebase Auth and start using some of the other paid products that Firebase provides.
1:47But hey, I'll take it. This is something you generally don't get from other Auth providers. Now the one exception to this is, of course, if you're using cell phone authentication, that kind of stuff, in which case it costs you money. Because you're actually sending texts to users phones. But in general, for any kind of password-based authentication, for OAuth, et cetera, Firebase Auth is free, regardless of how many users you have. So that's the first main benefit.
2:19The second main benefit is that Firebase Auth takes care of nearly all the complexity behind implementing user authentication. So user authentication is obviously a very complex thing. And you have to worry about lots of security things that really has a huge influence on how your company behaves. If you're creating a startup, you have to worry about keeping all your data secure, et cetera. And those are things that you have to worry about anyway. But the fact that you can just kind of give Firebase your users, passwords, emails, et cetera, and know that you have Google protecting all of that-- you have basically a team of people who spend all day every day, making sure that those things are secure-- that to me, is a very comforting thought.
3:04So security is the second main benefit of Firebase Auth. It makes it so that you don't have to implement your own authentication, you don't have to store users passwords, et cetera. And the third main benefit of Firebase Auth is that in general, it's incredibly easy to use. Now what you're going to see when we actually add this to a React project, is that essentially in order to log a user in Firebase, all you have to do is call a single Firebase function, which will actually log them in.
3:38And it'll take care of keeping track of all of the tokens, storing all that stuff in your browser, et cetera, behind the scenes, without you even having to think about it. Literally all you do is call Firebase's log in and log out functions to log a user in or out. Very straightforward-- and I think you're going to like it. So those are the main benefits of Firebase Auth. We're going to see these all in action. So let's jump into seeing how this is going to work in a React project. I hope this has been informative for you. And I'd like to thank you for viewing.
Creating Pages
0:08OK, so now that we know what Firebase Auth is and some of its benefits, the next question is, how do we add it to a React application. Well, in order to answer this question, what we're going to do is we're going to create a new application from scratch. And we're going to see how to install Firebase, how to set it up, how to create the login pages that are necessary, and that's about it. So let's get started. We're going to generate our project by saying npx create-react-app. We're going to call this project firebase-auth-basics.
0:40And we're going to add the use use-npm flag, because we want to use npm as our package manager instead of Yarn. You don't have to do that, but that's going to be my preference here. So let's hit Enter, and that will generate a React project for us. And once that project's been created, the next thing that we're going to do is open it up in our IDE. What I'm going to do is just say cd firebase-auth-basics. And I'm going to open that up in Visual Studio Code.
1:12And there we have it. So what we're going to do first is we're going to create the pages of our application. And really right now, we're just going to have two main pages. We're going to have the Login page. OK, this is just going to be fairly straightforward. It's going to have text box for putting in the user's email and one for entering in their password and a button that will let them log in. And we're also going to have a Home page, which is just going to display some basic information about the user, right?
1:43So it'll display things like their email, their user ID, et cetera. And we'll see how to add some other stuff to this a little later on. But the main point of what we're going to be doing here, after we've created these two pages, is we're going to see how to make it so that only authenticated users can access the home page and only users who are not authenticated, right, users that need to log in, can access this Login page. So in other words, we're going to see how to specify routes that users can only access when auth-ed or unauth-ed.
2:18So in order to get started with that, let's create a new folder called Pages, which is going to contain all of the pages for our application. And inside here, we're going to create our LoginPage.js. And we're going to create our HomePage.js. And just as a side note, one thing that always kind of confuses me and throws me for a loop is the casing behind login. Now the difference here, the difference between Log In and Login is that Log In, this is supposed to be a verb, linguistically speaking, and this is supposed to be a noun.
3:04So essentially-- so in other words, when we say LoginPage up here at the top, we could really choose either, right? We could either say this is the page that allows users to Log In, as a verb, or we could say this is just the page where the Login happens. So anyway, I just wanted to point that out, because you might see that throughout this course. I end up using these interchangeably, and it can definitely cause a few typos and a few errors when you end up capitalizing an I and you say LogInPage instead of LoginPage with a lowercase I, et cetera.
3:44Stupid thing, but I just wanted to point that out. Anyway, let's get started creating our pages here. Each one of these is going to be fairly straightforward. For the login page, what we're going to do is we're just going to say import useState from react. We're going to be using this for our text inputs-- right, the email and password text inputs. And then we're going to export our page by saying export const LoginPage.
4:16Again, we're using a lowercase I. If you want to use a capital I, be my guest. And it's not going to take any props. It's just going to basically return some jsx. OK, we're going to put this all inside a React fragment. OK, and then we're going to have an h1 heading where we say Login. And under that, we're going to have an input. The placeholder for this input will be "Enter your email...". And then we're going to have a value, which will be a State variable.
4:48And we'll also have onChange, which will be a state variable. We'll come back to those in just a minute here. Now underneath that, the next thing we're going to do is have another input, which is going to be a password input. So we'll want to add type="password" to this, so that it doesn't display the letters, it'll just show those little dots instead. And for this one, we're going to have the placeholder say "Enter your password..." And we'll have a State variable for that one as well. Now below these inputs we're just going to have a button, which, when clicked-- we'll say onClick-- is going to basically call a special login function that will define up here.
5:27So we'll just say const logIn. And here's a case where we end up using this as a verb, because this is actually telling our component to log in. We're specifying it as an action. Again, stupid thing, don't worry too much about it, but I just wanted to point out why there's that case difference there. Anyway that's going to be called when this button is clicked, we're going to say logIn. And for this button, we'll also say Log In with a capital I, because, again, the text of buttons is usually a verb and Log In, two words, is the verb form of this.
6:05So anyway, that's our login button and the rest of our elements for our login page. So let's actually create the State variables for our email and password inputs. We're going to say const email and setEmail equals useState. You know the drill here, empty string. And for password, we're going to say const password, setPassword equals useState empty string. And then down here, we're going to say value email, onChange e.
6:40We're going to do setEmail, e.target.value. Same thing here for our password input, value is going to be equal to password and onChang is going to be setPassword to e.target.value. Pretty straightforward React form stuff. So the next thing that we're going to do-- well, right now what I'll do is I'm just going to do something that you probably don't want to do in production. We're going to just display the email and password when the user clicks that button, just to make sure that we have everything hooked up correctly.
7:13We're just going to say alert, and we're going to say email, email and password, password. And that should happen again when we click on this Log In button here. So that's going to be our login page. And we'll test that in just a minute, when we add routes. But first, let's add a home page. For now, it's going to be super simple. We're just going to say export const HomePage equals-- it's not going to take any props.
7:46And it's just going to say return. And we'll just have an h1 heading here that says Home. OK, so pretty straightforward stuff. The next thing we're going to do is actually add routes for each of these pages. And we're not going to do the thing yet where we actually prevent a user from going to a route if they're authenticated or not authenticated. But we will get to that very shortly. So first, we're going to need to install the React router DOM package. We've looked at this earlier.
8:17If you're not familiar with it, I recommend going back and taking a look at it. So first of all, we're going to say npm install react-router-dom and hit Enter. And that will install that package for us. So now all we have to do is-- we're just going to open up App.js and add routes for both our Login and Home pages. What that's going to look like-- we're just going to remove all of the basic boilerplate that they gave us when we generated our project.
8:47I'm just going to adjust the indentation here. There we go. And I'm going to delete the logo and App.css. And what we're going to do is just import the BrowserRouter as Router. We're going to import the Switch component and we're going to import the Route component from react-router-dom. And we're going to use those components to display both of our pages at their corresponding routes. So what this is going to look like, we're just going to wrap everything inside a BrowserRouter here-- or Router, rather, since we renamed it up in the Imports.
9:25We're going to wrap everything in a Switch to make sure that only one of our routes displays at a time and that our routes re-render correctly when the route changes. That's something we'll talk about later on. And finally, we're going to display a route for each of these. We're going to say Route. For our home page, the path is going to just be a regular slash, and we're going to have to say exact there to make sure that only shows up when it's exactly that route. And under that, we're going to display our HomePage, which was just automatically imported for me.
9:57And next up, we're going to define a route for our login page. This one's going to look pretty simple. We're just going to say path=/login. We don't have to say exact there. And we're just going to display the LoginPage inside of there, which, again, was automatically imported. OK, and just to make sure that everything works, let's run our application now. We're going to say npm run start and hit Enter. And that should run our application for us.
10:30OK, so what we're going to see is that the home page shows up at localhost:3000. And if we go to localhost:3000/login, we'll see our beautiful little login page, which doesn't really have any styling or anything, but nevertheless, it'll work for our purposes. And also note that you probably won't see these little things here. That's just for my password manager, so just ignore those for now. So anyway, let's just enter in something for our email. I'm just going to say shaun@gmail.com. And for password, I'm just going to enter in something simple.
11:03And if we click Login now, we should see that we have both our email and our password that are being correctly picked up on by our login page. So those are the two pages for our application. I hope this has been informative for you and I'd like to thank you for viewing.
Redirecting Unauthenticated Users
0:10So at this point, we have both our login page and home page, which are being displayed at their respective routes. So now, the question is how do we make it so that users can only visit the home page if they're authenticated? And they can only visit the login page if they're not authenticated? So there's actually a few different ways we could go about this. One way that we could go about this, which is generally considered to be the more complex and error-prone way, would be inside each page to actually check if a user is authenticated.
0:44And if they're not authenticated, then basically redirect them back to the login page and vice versa for the login page. We want to check if they're authenticated. If they're already authenticated, we want to send them to the home page. So the way that we can do this in React is by using a special component from the React router Dom package, which is called redirect. So essentially, what this redirect component does-- I'm just going to import that here. Import redirect from React router Dom.
1:15Essentially what this component does is if it gets displayed inside JSX, inside the JSX of any component, it will try and redirect the entire application to a different URL. To show you what I mean here, let's imagine that our home page is checking to see whether or not our user is authenticated. For now, we'll just say const is authed equals false. Let's just imagine that they're not authenticated, so we'd want to redirect them. What we could do in this case, if we wanted to use this redirect component now, is we would basically say return is authed.
1:54And basically, if the user's authed, we're going to return the regular home page. Otherwise, what we would do is we would return the redirect component. Now, the redirect component, what it looks like when we display it in JSX. We say redirect, and it takes a single prop called to, and that will basically tell the application where to redirect to, as you might have guessed by the name of the prop. So essentially what this will do is if is authed is false, which, just for testing purposes, we've set it to false here, it will display this redirect component.
2:33Which will automatically redirect the user to wherever we specify here. So in other words, if is authed is false here, we're going to send the user back to the login page. To see what this looks like, what we're going to do-- Our application's still running, so let's just head back and take a look. If we try and go now to localhost 3000, what we're going to see is that immediately it redirects us to the login page. So that's exactly what we want with that, so everything's working out well there.
3:06So let's do the opposite now with our login page. Our login page, what we could do, is we're going to do the same thing. We're going to import the redirect component from React router Dom. I'm not sure why it wanted to import that from React router because that wouldn't work. But anyway, the next thing that we're going to do is say const is authed, and again, just for testing purposes here, we're going to say equals true. So we're going to simulate what would happen if the user was already authenticated.
3:37And just to make this work, let's change is authed to true here as well, so that it doesn't get it stuck in an infinite loop of redirecting back and forth between these two pages. And then what we would do is we would just say return is authed. And if the user's already authed, in that case, what we want to do is display the redirect since we don't want the user to be able to visit the login page if they're already authenticated. So we're going to say redirect to, and we would send them to the home page in this case.
4:12And that's all we'd really have to do on this page. So the next thing, let's just test this out, I suppose. We'll try and go to /login and hit enter. And sure enough, it will just automatically redirect us to the home page. So that's one way of doing it, and as I said before, this is generally considered to be the more error-prone way of doing this. Now, you might wonder why that is because honestly, the logic that we've written here seems pretty simple. It's literally three lines that we've added to these components.
4:44Well, the reason that I don't recommend doing it this way is because in general, the logic for redirecting users and authenticating all that kind of stuff gets a lot more complicated than what we have here. This is the nice, clean, shiny, new application here that only has two or three lines for this logic. But in general, things can get pretty complex. Imagine that, let's say, different users had different permissions, and you only wanted admins to be able to visit a certain page.
5:17And you only wanted non-admins to be able to visit another page, and you only wanted members of some group to be able to visit the group page. So on and so forth. The point here is that with this kind of logic, we generally want to encapsulate it inside its own component. So that's what we're going to do. What we're going to do instead of actually having each page worry about its redirecting logic is inside our app component, we're actually going to use a different component than this route here.
5:47Essentially, we're going to just create our own component, which we'll call authed route and unauthed route. So we're going to create two here, and those are basically going to be what take care of all the redirecting logic. And that'll leave our pages free to just be happy, carefree little pages and not worry about all this big bad user authentication stuff. So let's see what that would look like. What we're going to do is create a new folder inside our source folder, which we'll call components here.
6:20And we're going to create two new components inside of here. One of them, as I said, is going to be called authed route, and the other one, we're just going to give it the name unauthed route. Not super creative, but it works, and here's what these are going to look like. Essentially, each of these, we're going to say export const authed route. Each of these components is going to take some props. First of all, it's going to take a prop specifying whether or not the user is authenticated.
6:51So we'll say is authed, and then it's just going to take the rest of the props that get passed to it. You'll see why it does this in just a second, but we do need to get all of those other props by using the spread operator here. So the next thing that we're going to do, we're going to use that same redirect component that we saw earlier from React router Dom. So we'll say import redirect from React router Dom. And all we're going to do for this authed route is we're going to check if the user's authed, and if they are, we're going to just return a regular route component.
7:31Otherwise, we're going to return a redirect component. So in other words, what we're going to do is say return is authed. We're going to use a ternary operator here, and we're going to say if the user is authed, we want to just display a regular route. And here's why we did the spread operator thing with the props. We're just going to pass all of the props through to our route component by saying ...props. And essentially, what that'll do is if the user is authed, this thing is just going to behave exactly like a regular route component.
8:10So that's if the user's authed, otherwise we want to display that redirect. So we're going to say redirect and send them to the login page, where they will have to put in their email and password. So that's our authed route. Our unauthed route is going to look almost identical to this one, except it's going to be reversed. So what I'm going to do is just copy and paste this code here, paste it into unauthed route. We're going to have to change the name here, unauthed route. And essentially, we're just going to reverse these things by putting the route below the redirect.
8:42So in other words, if the user's already authenticated, we're going to redirect to, and we're going to change this to the home page here. So if the user's already authed, we're going to send them to the home page. They don't need to be at this unauthed route. Otherwise, if the user is already authed, it's just going to behave exactly like a regular route. So now that we have our authed and unauthed route components, let's actually add those to our app component. And the way we're going to do that, we won't need this route anymore.
9:15I'm Just. Going to remove that. Oh, and actually, now that I-- now that I've done that, I realized that we have to first import the route component into both our authed and unauthed routes. So let's just say import route from React router Dom. I'll want to put that right here. Redirect and route. And same thing for unauthed route. We're just going to say redirect, and we want to import the route component as well. So now in our app component, we're just going to import both of those routes we defined.
9:49We'll say import authed route from ./components/authedroute. Same thing for our unauthed route. Import unauthed route from components/unauthedroute. And now, we just have to replace these things with whatever we want-- whatever the equivalent component here would be. For our home page, this is strictly an authed route, so we're going to replace the route here with authed route.
10:23And for our login page, this is going to be an unauthed route. So oops, I changed the wrong one there. Unauthed route and unauthed route. And I forgot to do this one. Authed routed. There we go. So now, this should all work without either of our pages having to know about it. So what we can do is just delete the redirect from both our home page and log in page. So we're just going to return the home heading in this one just like that.
10:59And here, let's remove is authed as well. We don't need that, and in our log in page, we're going to remove redirect. We're going to remove is authed. We're going to remove this redirect, and we're just going to return the regular JSX from before. So everything should be working. It doesn't look like we have any errors. Let's take a look now at our application. Oh, first what we need to do is actually pass in is authed from our app component. So as you're going to see, what we're going to do here is have our app component be the one, at least temporarily, that controls whether or not the user's authed.
11:36So what we'll do is say const is authed equals, and let's just try it with false first. So for this one, for the authed route, we're going to have to pass in that is authed prop that we defined. So is authed is oft, and for unauthed route, we're going to say is authed is authed. And now it should work. Let's just go back here, and if we try and go to the home page now, what you'll see is that it doesn't let us.
12:06And likewise, if we change is authed to true, there we go. And I'm going to save it. What you'll see is that it won't let us go to the login page. It automatically redirects us to the home page. So that's how we create both auth-only and unauthed-only routes in React. I hope this has been informative for you, and I'd like to thank you for viewing.
Signing In With Firebase Auth
0:08So now that we've got our application pretty much set up to handle authentication logic-- We've got these routes that automatically redirect users. We've got a login page, a home page, et cetera. Let's actually see now how to add Firebase Auth to our application, so that we can allow users to log in with their email and password. So the first thing that we're going to do here is install the Firebase package into our front end. So we'll say NPM install Firebase, and we just install the entire Firebase package like that.
0:43Firebase Auth is just a subset of that we end up using. You'll see what that looks like in just a minute here. But while that's installing, let's actually head over to the Firebase console because what we need to do in order for Firebase to really work in our React app is we need to set up a Firebase project that will basically take care of managing all of our users, storing all their emails, passwords, et cetera. So what you're going to want to do is go to Firebase.google.com, and you're probably going to have to log into this if you don't already have a Gmail account.
1:18And what you're going to do is essentially just click on go to console here up in the right-hand corner, and that'll take you to what's called the Firebase console. Basically, this is your control panel for all of your Firebase projects. So what we're going to do here is create a new project, and you see I already have this Firebase Auth Basics one here. That's just the one that I was using for testing earlier, so ignore that one. What we're going to do is click on Add project, and then we're just going to have to give Firebase a few details about our project.
1:50So the first thing is going to be the project name. Now, this one can be really anything we want it to be. It's just an internal identifier, so no users are going to see it. So what I'm going to do is say React Firebase Auth Basics. I don't think that's what I called my other one. And what you'll see is that as you type that, you have this little thing down here that appears as well. Now, this is the project ID. And this is something that you cannot change and that the user may see, so you're going to want to be careful about what you end up having here.
2:25Don't go putting in any inside jokes or anything that you don't want users to see. Generally, Firebase will just generate something automatically for you. It does have to be unique across all of Firebase, so you may well find that your favorite string there is already taken. Now that we've done that, we've put in the project name. I'm going to leave the project ID the way it is, and we're going to click on continue. Next thing it's going to ask us if we want to have Google Analytics enabled for our Firebase project.
2:56I'm going to turn that off since that's just added complexity that we don't really need right now, and I'm going to click on create project now. So this little spinner thing is going to run for a little while, and once it finishes, we're basically going to have to add what's called an application to our project. So let's click on continue. And sure enough, right under where it says get started by adding Firebase to your app, you're going to want to click on this web icon here.
3:26Now, first of all, just as a side note with Firebase, Firebase does let you add iOS apps, Android apps, and even games that you create with Unity. And it allows you to basically use Firebase's services for those things. But for now, since we're developing a web application, we're going to use this web app. And applications in Firebase, by the way, are just another word for platforms. So you could have, as we saw, an iOS application, an Android application, a web application, et cetera.
4:04So we just need to let Firebase know that those exist here by basically creating one of those for our React app. So for our app nickname, we're going to say something like React Front End. We're going to leave this Firebase hosting thing unchecked. That is another service that Firebase provides for us if you're interested in that. Basically, it will host your app for you. But we're going to leave that for now, and we're going to click on register app. That will spin for a second or two, and then it will spit out some code here.
4:34So we already ran NPM install Firebase in our front end, so the next thing that we have to do is copy all of this code that they gave us here. I'll describe what it is exactly in just a minute. But let's just copy that right now, and we're going to head back over to our React app and open up the React entry point. So that's this index.js file here. So what we're going to do is paste this code now into index.js before where we say reactDOM.render.
5:07And then we're just going to delete these comments. We don't need those. And we also don't need app. We can just say initialize app Firebase config. So what is going on here? Essentially, what this Firebase config thing is, it just contains some unique identifier strings that will basically tell our React project what URLs to contact and what IDs to use in order to actually allow our users to log in, in order to do database stuff if you end up going with Firestore, et cetera.
5:42So these things here-- Also, they're not sensitive information. These are public information that gets sent to the client anyway. So don't worry. It's perfectly fine to commit these to GitHub, so don't worry just because it's a big long random-looking string. It's not actually a secret key. Anyway, that's how Firebase is set up. Essentially what this does, again, it tells our application all of the unique identifiers and URLs for our Firebase project that we created.
6:13This project and app that we created over here in the console. And it just helps it link up correctly to those. So now that we've initialized our Firebase app, essentially, what we'll be able to do is in the rest of our application, in our components, et cetera, we'll be able to actually make calls to Firebase Auth. And that will allow us to create users, to let users log in, et cetera. So let's first just go back, though, to our Firebase console.
6:44We're going to click continue to console, and that should be about all we need to do. So the next thing that we're going to have to do is inside our login page, we're going to have to add a little bit of logic that will allow a user to actually log in. Now, where this is going to happen is inside this login function here. We're going to remove our alert, and instead of doing that, we're actually going to make a call to Firebase, to Firebase Auth, telling Firebase Auth to log in the user with the corresponding email and password.
7:23So first of all, what we're going to need to do is import a few things from Firebase. So we'll need to say import, getAuth, and sign in with email and password. That is, as you may have guessed, the function that will call to actually log in the user, and those are both imported from the Firebase package and specifically /Auth. So that's a subpackage of Firebase.
7:53So now, inside this log in, what we're going to do, it's going to need to be an asynchronous function, first of all. And what we're going to do is just say const auth equals getAuth. This basically just gets a reference to Firebase Auth. And then what we're going to do is say await sign in with email and password. We're going to pass the auth object to this as an argument. So auth. And then the second and third arguments are the email and password that we've collected from the user here in our login page.
8:27So we're going to say email and password, and that will take care of logging our user in. So just to show us that that's actually happened successfully, we're going to say alert, and we'll say successfully logged in. And that should be about it. So before the user can actually log in, however, we're going to need to actually create a user in Firebase Auth, so that will have a matching account with the email and password that we're going to use.
9:02You'll notice that we haven't yet created a create account page over here in our pages folder. That's something we'll get to later, so don't worry about it. But for now, what we can do. We're going to go into authentication in our Firebase console. We're going to click on this get started button here, which should activate Firebase Auth for our project, and then down here in this box, you can see that these are what are called sign-in providers. Basically, these are just different ways that you can allow users of your application to sign in.
9:37So you can see that in addition to email and password, which is what we're going to be using here, there's also Google, Facebook, play games, game center, Apple, GitHub, Microsoft, blah, blah, blah. There's a lot of different providers that you can use to allow users to log into your application. And that's something that we'll see later on as well. But for now, let's just select email and password. We're going to flip this little switch next to email and password up at the top that says enable. We're going to click on save, and that's all we should need to do.
10:07So now that we've activated this email password provider, what we're going to do is click on the users tab up in the top left. We're going to click on add user, and here's where we're going to add the first user to our application that we're going to actually be able to log in with. So for the email, I'm just going to say Shaun@Gmail.com, and for the password, I'm going to say ABC123!. We can click on add user now, and that will create a new user in our application.
10:42Now note also that this is not something that you'll generally do. Creating accounts for users, unless you're working in a very exclusive application where users have to actually contact you before you can create an account for them. You're probably not going to be doing this. The only reason we're doing this here, again, is just because we don't yet have a create account page. So now that we have this account, let's see how we can log in with it. What we should be able to do is just go to our login page.
11:12Here. What we're going to need to do first is actually change isAuthed to false. Oops. We need to run our application again. We'll say NPM run start. And there we go. We can see it goes immediately to our login page. So let's enter in the email that we created the account for. Mine is Shaun@Gmail.com, and then for the password, ABC123!. And now let's click logged in, and we should see successfully logged in logged out through this alert.
11:48So when we click OK, we are, at this point, going to be logged in. However, because we're just using a hard coded variable inside our app component, we're not going to see any changes reflected, and that's something that we'll take a look at shortly. We're going to need to actually have Firebase listen for changes in the user's auth state. But anyway, those are the basics of logging in with Firebase Auth. As you can see, it's super easy. It's literally just one function call that takes care of most of that for you. I hope this has been informative, and I'd like to thank you for viewing.
Listening for Auth Changes
0:08OK so now that we have users able to actually log into our application, right, by using this sign in with email and password function, that Firebase auth provides to us, the next thing that we need to do is have our application actually update when that event occurs, right? So in other words, when the user successfully enters in their email and their correct password, we want to have our app actually know that happened, and redirect the user automatically to the home page. Now the way that this is going to work is inside our app component, we're actually going to have a state variable.
0:45And we're going to call this state variable user and setuser. You'll see why that is in just a minute. And here, let's just import useState up at the top while we're at it. UseState from react, and then we'll say useState, and the initial value of this is going to be null. OK so essentially the way that this is going to work is Firebase provides us with a function called onAuthStateChanged, that basically allows us to set up a subscription that will listen for changes to Firebase's authentication state, right?
1:21In other words, when a user logs in or logs out, the callback that we passed to this function will be called with the user that just logged in, right? A Firebase user object, you'll see what that looks like shortly. So the way that we use this, first of all, we're going to import that from the Firebase package up here at the top. We're going to say import, getAuth, and onAuthStateChanged. That's the function that I just told you about, that allows us to set up that subscription.
1:51And we're going to import those from firebase/auth. Now the other thing that we're going to need to do in order to set up a subscription in pretty much any react component, we want to do that inside a useEffect hook. So let's import useEffect from react up at the top. And we're going to use that now to actually set up this subscription that will allow us to keep track of this user thing. So we're going to say useEffect, and for the useEffect callback, we're going to create our subscription.
2:24So we'll say const auth equals getAuth, right? We're getting that reference to Firebase's auth object. And then what we're going to do is say onAuthStateChanged. We're passing auth as the first argument, and as the second argument we pass a callback. And this callback will actually get the user, the currently logged in Firebase user object, as an argument.
2:54And then, what we need to do is inside this callback, we need to set our user state appropriately. So basically what's happening is that when the user first opens up our application, right, and we have user and setUser equal to null, that just means that our user is initially unauthenticated before they actually log in. So what we're going to do is when this changes we're just going to say setUser to user, and that's about it for now.
3:25So the other thing that we need to do now is, since we no longer have an isAuthed variable, right, we just had that as a hard coded variable before. We're actually going to use this user, right, the user state, to tell whether or not the user's logged in. And that's actually pretty straightforward to do, because again all we have to do is check if this user exists. If the user doesn't exist, that means the user is not logged in. If the user does exist, it means the user is logged in. Simple as that. So what we're going to do is for isAuthed, for both our authed and unauthed routes, we're going to pass through double exclamation point user.
4:04Now what this double exclamation point does, if you haven't seen this before, is basically it just takes any value in JavaScript and converts it to a Boolean. It's basically asking, does this thing exist? And if user's null, this will be false. And if user is an actual object, this will translate into true. So just wanted to point that out there, in case you weren't familiar with that syntax. And that's pretty much all we have to do. So if we go back to our application now, we'll see that since we've already logged in, we're on the home page.
4:37So what you might want to do here is, if you want to test this, since we currently have no way to log out, you can always just open up an incognito window and go to localhost:3000. And that will basically allow you to see the page without any of the stored credentials. So what you can do is just test out the login here by saying shaun@gmail.com, entering in your password, clicking log in. You'll see successfully logged in. Click OK, and that should send you now to the home route.
5:07Now one thing to notice is that it's sending you to the home route automatically, not because we are saying history.push or anything, right? We don't even have history inside our login page. It's happening automatically because of the logic that we have inside our authed and unauthed routes. OK, essentially those are detecting this change to isAuthed, right? There is authed prop, and automatically taking care of all the redirection logic. So we don't have to do that kind of logic inside our home and login pages with the current setup that we have.
5:43All right, now one last thing that we are going to want to do is make sure that, while our application is actually loading, it doesn't display the login page, right? You might have noticed that if you refresh, it'll automatically show the login page. Because, again, our user is initially null while our application is taking care of actually logging the user in behind the scenes. So what we need to do is basically we need to have another state variable here, which we'll call isLoading and setIsLoading.
6:19And what this is going to do is basically while our app is checking whether the user is logged in, right, it's checking with Firebase, this is going to be true. And once we see that either the user is or is not logged in, right? Once we find out for sure from Firebase which is the case, we're going to set isLoading to false. So what this is going to look like, the initial value for isLoading is actually going to be-- we're going to need this auth thing down here. We're going to need to say const auth equals getAuth.
6:50And the initial value here is going to be basically whether or not the current user exists on auth. Now what I just did here, this auth.currentUser thing, this is just a property that contains the current user object that's logged in. Now note that since this can change over time, we don't actually want to use this for ongoing things, right? We won't want to say isAuthed equals auth.currentUser, because this thing could change over time, And that would not trigger a subsequent render in react.
7:28But in our case here, it's perfectly fine to use it as the initial value for a state variable. All we're doing here is, if there's already a current user, we're just going to set isLoading to false. If there's not, we're going to set isLoading to true, because that means we don't really know whether the user is already logged in or not. And we're going to do something similar for the user down here and useState. We're going to say equals useState, and the initial value for that is going to be auth.currentUser.
8:01So essentially, if the user is already logged in, and we already have auth.currentUser, we're not going to see that loading state. Otherwise, we're going to see a loading message, which we actually have to display down here. The way we'll do that is just by saying return isLoading. If it is loading, we'll just say loading, dot dot dot. Otherwise, we'll display the regular JSX. So the other thing that we have to do is, after we've set the user, we need to say set isLoading to false.
8:35So that in case it was true to begin with, and it will be a lot of the time, it will turn to false once the user is actually logged in. Now this will work as is right now. Right, if we click refresh, we'll see loading and then home. Loading, home, loading, home, et cetera. One more thing that we have to do, just for cleanliness sake, and to prevent memory leaks, is we have to make sure to cancel this subscription when our app component rerenders. So essentially, what we're going to have to do is this onAuthStateChanged function actually returns a function that will cancel the subscription for you.
9:13So what we'll do is say const cancelSubscription equals onAuthStateChanged, blah, blah, blah. And then we're just going to return the cancelSubscription function from this useEffect hook, which basically means that this cancelSubscription thing will be called when our component unmounts. And the last thing we need to do here is, since we only want to set up that subscription once, we're just going to pass an empty array as the second argument to useEffect OK, so this should all work now.
9:48And if we open up the inspector window here in console, we shouldn't see any kind of-- ah, here. So this one warning just says that we need to pass auth as a dependency, just in case that changes over time. It shouldn't, but just to make react happy and to get rid of that warning, why not? OK, and everything seems to be working now. The last thing that we're going to do here, and this is a very, very simple thing to implement, we're going to add a logout button, so that we can actually log out of our application.
10:18So what this is going to look like is inside our home page-- we're going to open that up. What we're going to do is just add a basic logout button to the bottom of the page, that will allow the user to click on it and actually log themselves out. OK, now in order to make this happen, we just need to import getAuth and a function called signOut from the Firebase Auth package. OK and we're going to basically create a function here called logOut.
10:50It's going to be an async function that will basically call this signOut function for us. So what we're going to do inside of here, we're going to say const auth equals getAuth. We're going to say await signOut, and pass auth as an argument. And then we're just going to display an alert that says something like, "Successfully logged out." OK and then we just need to wrap these in a react fragment to make React happy with our syntax. And we'll have the button call this logout function by saying onClick equals logOut.
11:25And that should be our logout button. So as you can see, the logic here is incredibly simple for logging out a user, and essentially all that does is just delete some tokens behind the scenes that Firebase is using to create the user session. So let's go over here to our home page. Now we can click Log Out. We should see successfully logged out, and we'll see that has automatically now redirected us back to the login page. So just to go through the flow one more time, we'll say shaun@gmail.com, abc123, log in.
11:58Successfully logged in, and we're at our home page. So everything seems to be working just fine now, and we've successfully added Firebase Auth to a React application. So I hope this has been informative for you and I'd like to thank you for viewing.
Frequently asked questions
What does the Firebase Auth Basics lesson cover in a React app?
The lesson explains what Firebase Auth is, then walks through creating a Firebase project in the Firebase console, initializing the Firebase config in a new create-react-app project, and building Login and Home pages. Learners sign users in with email and password, listen for auth state changes, and redirect unauthenticated users with a dedicated route-protection component.
What should a developer know before starting the Firebase Auth Basics lesson?
The trainer frames the lesson for people already familiar with React and basic full-stack concepts who want to add user authentication quickly and securely. The course overall is foundational-level and suits teams with no React experience, but learners should expect hands-on JavaScript and full-stack development concepts.
How long is the Firebase Auth Basics lesson and where does it fit in the Full-Stack React Development course?
The lesson runs 56 minutes within a course of about 27.5 hours per learner. Training Managers can assign the course in phases by topic area, MERN basics, server-side data, authentication, then the full app build, and this lesson sits in the authentication phase.
Why use Firebase Auth instead of building user authentication from scratch?
The lesson highlights two main benefits: ease of use, since signing a user in is essentially a single Firebase Auth function call, and security, since Google manages and protects users' passwords, emails, and related data. That lets a development team add authentication without managing the difficult parts themselves.
How do you protect React routes so only logged-in users can see certain pages?
The lesson first shows per-page redirect logic, then explains why it becomes error-prone as rules grow, such as admin-only or group-only pages. It moves that logic into its own component used in the app component, so each page no longer handles its own redirects.
How can a Training Manager track the team's progress through this authentication training?
Training Managers can group the course's topic areas with CBT Nuggets Playlists and use Team Reporting to see per-learner progress and completion, cohort and group views, and completion exports for audit evidence. This supports rolling out the authentication phase to the team on a planned schedule.
Team training path
Turn this skill into assignable team training
This free skill is a preview of the courses your team can assign, track, and report on with CBT Nuggets.
$59
seat / mo, billed annually
