NextJS + Firebase V9 Authentication tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone in this video let's see how can we do authentication in next year's application with firebase so i have opened an empty folder inside of a vs code and let's create a new nexus project with npx create next app at latest dot to specify to create this project in this directory and dash sds to say it has a typescript project will come back after it finishes so the installation has complete and we need some more packages for this project so let's quickly install them one is firebase and these are the these are just for styling purpose bootstrap and react bootstrap so let's quickly install them so packages have been installed so let's just create a firebase project so open your browsers and head to firebase.google.com and let's create a new firebase project so come over here firebase.google.com and click on go to console and here let's create a new firebase project click on add project and give a name i'm gonna say next firebase up and you can just click on continue and it asks for whether it should enable analytics let me just off it i just don't need it and then it will just create your project our project has been created so let's click on this continue and it will redirect to a particular project dashboard and here now we have to create a web app so click on this third icon that's for web so let's create a new web app in this project and we have to name our app next is firebase up and uh i don't want any hosting so i will just register my app and then we have to add the firebase sdk which we have already installed if you just remember we have installed firebase so let's just copy this whole thing and paste in our project and let's i've copied it and i'm clicking i have clicked continue to console and let's go to vs code and create a new folder called config inside of that i'm going to create a new file firebase.ts and let me just paste it there and i'm gonna just remove all these comments let me just say that in an ideal situation you shouldn't just expose these values you should probably putting them in an environment variables for but for this video i'm just gonna let it be here now let's open the terminal and spin up a dev server so open your terminal and run npm run dev to start a local development server at port 3000 so if you just head over to localhost 3000 we are going to see the basic project of npm we are going to see a basic next year's project so this is a starter project from next year's and now let's configure bootstrap so that we have some styling in our pages so go to the underscore app.tsx page inside of the pages directory and import css from bootstrap so that's import bootstrap slash test slash bootstrap.min.css so this will include the bootstrap styling for us so if you just refresh the page you can see we have the bootstrap styles by inspecting the element and if we see some global variables css variables of bootstrap then we can just say we have bootstrap yes as you can see we have this variables on the root element so we have bootstrap so now that we have bootstrap setup let's create few pages so head over to your vs code and i'm gonna create three pages so one is login.tsx and signup.tsx and dashboard.tsx and dashboard will be the page that we are gonna protect after authentication so um i entered that script and it created me three files and now i just want to paste some code so that you don't have to waste your time watching me doing some css so i have already prepared some code and i will explain you step by step what's going on here so i've i've created a i've pasted some code in this and this is basically login component and i'm i'm setting some state for email and password and then i'm rendering a form which takes an email and a password and this is a control field so i'm on change i'm taking the value and setting the state and we have on submit handler that's going to just log the data and similar thing goes to signup.tsx i'm gonna just paste some code here too and everything is same only difference is i have a different function names and different headings and dashboard uh it's fairly simple for now so this is this is it so we have our three pages so let's go and see how it's looking in the browser so if you just navigate to slash login and let me just close the dev tools okay uh this is a basic login form so nothing crazy is happening if you just see that in the console if we enter our email and if i just click login i'm gonna just get the data what i have typed and it would be better if we have a navbar so let me just create an app bar i'm gonna create a components directory and inside of that i'm gonna create a navbar.dsx and here too i'm gonna just paste some code so that you don't have to see this boring stuff so i have this nav bar and here i have a link to sign up and a link to login so that we use next year's router so that it doesn't do page refreshes so let's now include this navmar component in every page so let's go to underscoreapp.tsx and let's wrap this in a fragment and put our nav bar in here let's do our nav bar and let me just import it okay it's not giving some suggestions for me so let me just import it so we have a navbar now if you just go and check uh the browser you can see we have an app bar and we can just go to sign up and login and dashboard if you just go to dashboard let me just see we have the basic dashboard here so now let's do some interesting stuff with firebase so in this project we are gonna use react context so that our user will be our user will be available throughout the application so i'm gonna create a folder called context and inside which i'm going to create a file auth context dot tsx and in this file we are gonna have all the methods like login and the user in this particular context so first let's import some stuff from react and we are gonna need create context so that we create context and use context because we are going to create a hook so that we can use our context and first of all let's create our art context so that goes our context is create context and this needs a default value so we will just put a empty object and let's now create a provider for this uh context so it's gonna let's we are gonna export this so export const uh auth con context provider so this will take children a react children since we are going to wrap this in the underscore app file and let's just give some type children will be of type react dot react node and then uh we are gonna return uh auth context start provider uh odd context dot provider and we will render our children inside of here so the thing is uh artcontext.provider needs a value prop which is required so we are gonna just say the value is an empty object for now and typescript is happy with us now let's create a hook that we will be using to get the value out of this value object so it's gonna be called use auth and it's gonna just use our out context and we will need to export this object so we can use it else where in our application the magic of firebase authentication lies in a single function that listens for the change in the authentication state so let's just quickly bring that in from firebase auth and it's called on auth state changed and this is the function this most important function so we will be listening for the changes in the authentication state inside use effect so let's create a use effect and let me just import it whenever our app mounts we are gonna listen for authentication state changes by using our firebase on our state change function so let's do that uh this will return an unsubscribe method which is we have which we have to unsubscribe while we unmount our component so this function actually if you just see this function uh needs few parameters if you just check first one is auth which is actually the auth module which we have to initialize inside of our firebase so we haven't done it yet let's go to firebase config and inside of this we have to use our app and create a authentication helpers so let me just export auth equals get auth this is going to come from firebase auth and it's it's imported at top by vs code and for and i think we just have to put the const here and we got our authentication module here and we can just use it we it has many useful functions there and that we have to pass here on our state change this function requires auth that's coming from our config that we have just uh created and the next next parameter is a function is a callback function and this callback function has a parameter called as user and this will be the information about the user every time there is a change okay so let's just see what this user has so if you just type user dot and you can just see there are so many fields on this user like email display name and few methods like get id token and all all the stuff all the good stuff so why don't we just store this in a state right so let's initialize a state we will call him user and set user and let's just bring in the use date and initially it will be null uh let me just put any here for the time being and i will add types later so initially the user is null and then if we have a user when the authentication state is changed uh let's let's set the user to something meaningful so let's set the user to have yes i want a uid and i want to email and i want to discipline it yeah exactly thanks co-pilot for that and we got the basic information about the user else what we're gonna do is let's just set the user to know and while we unmount so we have to make some call to up unsubscribe so while we uh unmount this component we're gonna call to unsubscribe and this will remove all the listeners from the firebase now that we have user in our state let's just pass that to the value of the context so inside this object of value prop i'm gonna say user is the user so user value will be the user that we have instead so now before doing anything first we have to wrap our underscore app.tsx inside of our art context provider or else we will not have access to anything that context provides so let me go to underscore app.esx and i will import our context provider and i will wrap our whole thing in this odd context provider so now everything any page that renders will have uh will have access to value that we are passing here if we just use our hook user so when we use use hot we are gonna have access to value that we are sending in this so let's go to sign up dot sign up and let's check if that's the case so i'm gonna use r and the return value of this is user i think typescript is gonna complain me that user doesn't exist but we know it exists but let's just see if we get uh user as an null so because we don't have any user currently so uh as you can see we have a null here now let's create some functions that will help us doing authentication so i'm gonna create a new sign up function uh below the use effect so let me just collapse it so it's it's const sign up is it's gonna take an email which is a string and a password which is a string and we will return a simple function that we will call with firebase so go to top and import a function create user with email and password so let's do that and we are just gonna return this by calling with email and password it's that easy with firebase we just have to call this function with email and password but if you can see it's still complaining because the first argument it needs is auth so every function in firebase needs this auth as a first argument so similarly let's just create a login function it's pretty similar and let me just name it as login and here sign in with email and password and it's gonna import me from firebase and the third one is obviously logout and this doesn't need anything and it's gonna set the user as null and let's log out it is called as sign out from firebase so i'm gonna say sign out and this all function also needs art as its first parameter and let me just await it because it's an async function so if you just hover over this sign out you can just see uh it's it's returning a promise with void and i'm gonna mark this logout function as async and i'm gonna await sign out so now that we have all of our functions let's pass all of them to the value drop here uh first i'm gonna pass login and sign up and then log out so one thing we have to do here is we have to wait for the loading state what do i mean is uh even if the user is authenticated initially the user is null here so we have to wait until the we get the user from the firebase so i'm gonna put a loading state which is initially set to true so initially we will say that yeah this is loading and after we have finished this if else block whatever might be the situation of the user we will just say loading is false and then based on whether we are loading the user or not we are going to show our children so if it's loading then we are not going to show anything else we are going to render all of our children here let me just log log the user so we get to see what's the user value but you may have noticed inside of signup.tsx we are getting some kind of error that says property user doesn't exist on type empty object that's because we are using typescript and we haven't given any types to create context which actually decides what uh what react expect so here it takes a generic type for now i'm gonna just put any and i guess that would solve but yeah it uh they are gone for now but and then since we got everything working let's destructure signup function and let's add some functionality so here i'm gonna say this is as an async function and i will try catch i will try catch some uh our our request so if there is an error let me just log it or i'm gonna say await sign up with data dot email and data dot password similarly let me just log the error so that our app doesn't just crash away and i guess that's it so let's just go and try what happens in the browser so in the browser in the signup page we can just see in the console from the context.tsx page we are getting null as our current user because no one is logged in or no one is signed up so let's create a user and let's see if if authentication goes correct so i have given an email and a password and let's see if it's success okay we got an error and this error is a pretty important one if you just go and see what it's saying is inside of error message operation not allowed so basically we have to allow firebase that yes we want to have our users to email and password so we have to say it too explicitly to firebase so i don't head over to your project console in firebase and go to authentication tab and inside the sign in method tab here uh go to email and password since that is what we are using uh and click on enable and only this one this is uh passwordless sign in we don't need that for this tutorial so only email and password and click on save and then come back here and let me just do a quick refresh and i will just type the same email and password again and this time it should just create a new user and we can see that in the firebase console so i'm hitting sign up and if everything goes right yes we see our our context our user from our contest we have logged it in the art context so we can clearly see we have a user and it has a uuid i mean it it has a unique id and then if we come here inside of a users tab yes we can see our user has been created so as soon as user has been created we are logged into the session so if you just refresh the page you can see user is no longer null it actually starts so it's initially null because uh initially we don't know whether the user is authenticated or not until firebase says explicitly so we are rendering nothing on the screen if it's if that's the case and after loading is done we can see we have uh we have our user similarly let's implement the login functionality so i'm just gonna copy this and i will go to login.tsx and where we handle the submit here i'm gonna just paste and instead of signup we are going to call login function and that login is going to come from our use auth hook and user is going to come from our context let's import the login function and this should work perfectly fine now let's go to navbar and let's get the user and according to user let's show log out or sign in or sign up so okay there's a little error here i have to mark this function as async yeah that will solve the situation and let's go to nav bar here and let's bring our hook use author we will get the user information from here and here where we show some links here let's say if there is a user if there is an already user we're gonna show something different eventually i will add here a log out button for now just i am putting the diff with the placeholder else we are gonna put two links so that people can go and log in and sign up for our application so now if we have a user then we have we should have a button to log out if we don't have a user then sign in and login and sign up functionality so if that's if that's if that goes well let's check uh if we have a logout button yeah as you can see we have a logout there but it doesn't do anything right now let's go and add the functionality to log out so i will just put this as a as a link [Music] but we do we will not have any href or pass href uh i guess we don't need any next year's link and let's say on click on click we will log out and logout is going to come from uh use op after logging out let's just push the user to login page so i will say router dot push to slash login and router is from next year's router that's router is use router and we have to import use router and we got that from next router so after immediately logging out we are gonna push the user to slash login page so let's check if that's working uh let me go so since we actually signed up we are gonna see we are gonna see the user so let me just quickly refresh here actually this is not sign up this is log out so we should see log out here and if i just click it i have to go to login page as you can see we got to uh redirected back to login page here now i i can actually login with my user if i just type some random credentials or some wrong password or wrong email you can see we will get some nice error messages we can just catch them and show them to the users but in this tutorial we are not going to do that but let me just log in correctly after logging in what shall we do is we will push the user to dashboard so i'm coming here after logging in and pushing the user router dot push to slash dashboard so i have to get the router from from next js router so after logging in we are pushing to slash dashboard which will be this page currently this page is not protected and we will add that feature just uh in just in a minute so let me just hit uh let's put a email and if this goes right we will be redirected to login yeah we we got we got uh to dashboard page but uh now if i just click log out you can see if i uh navigate to dashboard by changing the url here you can see it's actually available to anyone even though he's not authenticated it's available so that one thing that we have to change uh we have to create a protector route so inside of the components i'm going to create a new component called protected route dot esx in this will add a very basic uh logic to identify if the user is there or not and according to that we will just allow if to allow the user to see the page so here what i'm gonna do is similar to our context we are gonna take children and children is of type react dot react node and we have let me just return children and here we have to add the logic for to check if there is any user so uh so i'm gonna bring our user from here let me just take the user and we will bring our router which is use router hook from next.js and inside of a use effect we are gonna see if there is a user and according to that we will take action so if there is no user i'm gonna do router.push login and here we have to uh say router dot push and also i guess we have to put a user as a dependency array and i think i have to import okay i got use effect there this shouldn't okay i think this needs router okay so what this is basically doing is if there is no user it's just pushing to login page and here let's just do a little more uh strict uh thing that is if here we will again check so that we don't have a flash content so if there is a user only then we are going to show children or else just we don't show and the main part comes here then we use this protector route inside underscore app.tsx so generally how i do this is um i will create some uh pages that uh array that and doesn't uh which has the routes that doesn't require any authentication so that's accessible to everyone so i will just put that inside of an array and and here i will just check the router the route parameter and if it's if it's not in this particular routes then i'm gonna protect that route so the logic goes something like this so if no auth required uh dot includes if this particular thing includes router so first we have to get router from next year's router if this array includes a path name then we are just going to show the component and if it doesn't include we are going to protect that route so how do we do that we will add pro protector route and let's close it and let's put our component inside of that and we have to import our protected routes and i guess everything's right now so let's now log in and see if our route is protected so let me just quickly refresh and if i just go to login yes that's a page here so i will log into my account and we are redirected to dashboard and uh this thing works right and if i just log out now if i go to dashboard not deal it's just dashboard you can see i uh we have to get redirected to login page as you can see we got redirected there so uh and that's a protector route functionality so this is the very basic way in which you can implement uh authentication in next year's app with firebase sure we can do a lot more things like error handling or some storing our data in a postgres database but this is a base baseline minimal thing that you can do to protect your routes and it actually works pretty awesome i hope you like this video if so you can just like and subscribe and if possible share it with your friends and see you in the next video
Info
Channel: Sairaj Chouhan
Views: 32,419
Rating: undefined out of 5
Keywords:
Id: ZmpO65DhRN0
Channel Id: undefined
Length: 33min 3sec (1983 seconds)
Published: Sat Feb 26 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.