Next Auth v5 Complete Guide in Next.js 15 with Prisma and MongoDB

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome back to another video on nextjs I'm going to be implementing complete authentication and authorization system using aujs version 5 which is the latest version of it and you can see that at the top it is showing migrating from next.js Varan 4 actually I've created the couple of videos already using the next Au verion if I show you my playlist so this is the playlist of my next4 tutorial app directory and you can see that it has this video next o login registration with credentials and GitHub and this is the second video on next o for forget and reset password implementation with mongodb all right so this is the application which I'm going to be implementing this is the Navar and this is the landing page which is the public page currently the middleware and the server routes are the protected because I'm not logged in if I click on the login uh I'll have this form and uh it has proper validation applied and if I click on login after giving the correct uh email and the password uh then I will be able to login and if user which is trying to login does not exist in the database it will first register itself in our mongodb database which I'm going to be using in this video and then it's going to be login uh performing all the session management thing okay and then I'm going to show you how we can add the login with GitHub and other social providers so let me click on the login uh you will see this awesome loading uh on that button and you can see that it has this email ID which is currently logged in we have a log out button now and if I click on the Middle where I'm able to navigate to this middleware and these server routes because I'm now logged in and uh if I click on the home uh this was already a public route all right I can click on the log out and now I can actually click on the login again I will not be able to navigate to the middleware and the server route and also I'll be using this Prisma omm for data modeling so three things which I'm going to be using actually Four uh nextjs OJs version 5 Prisma orm and mongod DB so let's get started by creating a new nextjs project in vs code so I've opened up an empty folder in my vs code first of all we need to verify that we have the latest stable version of node and npm installed in our system so in the terminal of vs code I can verify that so this is the verion I have currently installed which is fine so I'm going to be clearing this out and let's write this command npx create next app at latest space dot because I don't want to create a new folder in this particular folder which I've already opened so I'm going to hit enter so it's going to ask me few questions I'm going to start off with the typescript yes eslint yes Tailwind CSS yes Source directory no app router yes this is a very important point and and no for import Alias so this is going to create a new nextjs project so before moving further make sure you subscribe my channel and also if you need any development services you can contact me on LinkedIn I've given the link of my profile in the description of this video so this is still getting created actually I've created a nextjs project using App directory structure you can follow this video using the version 13 of nextjs using the version 14 version 15 that uses app Direct structure there are few differences between these versions but overall the structure and the layout is same so our next JS project is created let me clear the terminal out let me run the project and see if everything is working fine we have this default URL here and this should be visible on the Home Route so our project is running on Local Host colum 3000 Let me refresh this page currently I was running my old project so let me me hit enter and it should show me this default UI which is provided by nextjs so I'm going to be deleting everything which is provided by this so let me remove this and also let me add this div landing page for now okay let me save it and it should be automatically populated on this page uh sometimes it doesn't so I have refreshed it is showing landing page which is fine okay so before moving further I'm going to be installing all the packages and libraries which are required to be used in this tutorial so more than half of this video is about configuration of Prisma next o and different files and folder structure so I would request you guys to stay focused because I will be following the documentation plus I will be modifying the recommendations which are provided by this documentation of next o and also by the Prisma okay so first of all in the terminal I'm going to be installing few packages let's first install Prisma for/ client then I need to install Au Prisma adopter then I need to install mongodb let's also install o mongodb adopter okay for now let's hit enter I want these packages to be installed uh in our project so after that I need few more packages like the bcrypt for encryption of the password for icons using react icons um and a few more packages so let's wait for it until it gets installed so these packages are installed let's also install few more packages first of all we need bcrypt JS we have already installed mongodb so I would need react icons as well and also so I would need at type bcrypt JS let's hit enter and after that uh I will be installing the Prisma as a Dev dependency so let me install npmi Prisma hyphen hyphen save hyphen Dev let's hit enter so it will be installed as a Dev dependency in our package.json file once it is going to gets installed I'm going to show you in my package.json for now let me open this up so you can see that all of these packages are installed in the dependencies uh BCP type bcrypt mongodb react icons and in the dev dependencies we have this Prisma installed now one last but most important package is next o package which we need to install but for that let's go to its documentation aujs dodev let's click on get started and here we need to select different Frameworks we are using nextjs let's click on that so this is the command which we need to copy and let's run it in the terminal of our vscore so this is going to be gets installed as a beta version because this V5 version is the latest version which is in the beta stage so if I go over here we can set up different environments we need to create a EnV file in our project and we need to create this secret secret can be anything but it is recommended to use some complex X secret so first of all in our project we need to create a new file do EnV and inside it we need to create Au underscore secret equals to okay and in the terminal uh we can use any of these commands to generate the secret so we let's use this one the first one let's hit enter and this should actually give us yes you can see that it has given us this thing so I can actually copy whole thing let's paste it over here and uh since we have this equal sign let's wrap it inside the double codes okay let's go to the documentation let's come down and now we need to create this au. TS file so let's create a new file and this is going to be the o. TS uh for now let's copy everything which it is recommending let's copy this and let's paste it over here I'll be modifying it and I'll be adding a lot of lines of code in this particular file uh um for now let's leave it now we need to create this particular folder structure within the app directory so / API sl/ uh dot dot dot next o so let's create that inside the app let's create a new fold folder let's add the whole path and inside this particular last folder we need to create a new file route. TS route. TS and let's paste which is recommended by this now rather than actually first importing and then exporting it from here we can directly add this particular line of code over here here let's remove this const as well let's remove the first line let's save it currently it is showing some error because we have not added anything like get post within the .js file over here actually this is the TS file okay for now this is pretty much it we need to add in this particular file so let's close it and let's go to the documentation what we have here we need to create one last file which is the middleware dots uh it has given us one line let's add that I'll come back to this file and I'll be adding a lot of things inside it so let's close it let's close all of these files and one last important file is this one au. TS okay so let me add few lines of code inside this file so first of all inside the providers we need to add import GitHub from next o providers GitHub okay so this has been added uh this has to be with the capital G actually okay and after that uh we can import Prisma adopter from o Prisma adopter and then we need to import credentials credentials are going to be from uh next o provider credentials so this is going to to be with the capital c don't do any kind of mistakes and uh finally we will be needing this bcrypt JS actually bcrypt from bcrypt JS okay and here inside this Handler we can have this as an object and let's add get and then the post let's save it so we have Handler get post sign in sign out Au and inside the providers we can have a GitHub provider like this and then we can have the credentials provider which we have already imported so credentials like this okay and inside this GitHub we can have this client ID and the client secret like this and these are the different uh variables which we need to add I'm going to be changing the name of this in our EnV file so let me change the name so Au GitHub ID or GitHub secret okay and here above this provider we need to add an adopter this is going to be Prisma adopter and then I'm simply going to pass a DB which I yet need to create and one thing which I need to add here is this strategy which is going to be the JWT okay so now let's create this DB file and DB file should be existing inside any folder or we can have it directly in our root directory so DB dots okay and inside it we can actually import Prisma client from Prisma client since we are using nextjs nextjs have the server side rendered components or a client side rendered components uh actually the documentation of next o if we go to this authentication or let's say the database Prisma and this is what it recommends to add in .ts directly Prisma but we are using nextjs it doesn't quite work well in nextjs when we have the server side rendered component or client side rendered component so we need to create a global variable to make it work so I first need to declare that declare Global and then inside it we need to create V Prisma which is going to be of type Prisma client and undefined and after that we can have export con DB global do Prisma and the new Prisma client by the way the extension which I'm using which is recommending me all the cool code uh by reading the context uh is this one let me show you this one super Maven make sure you install it it has its paid verion as well but I'm using free verion and free verion is quite good uh so let's come over here and let's hit enter so it is recommending me few things and it is giving me the correct line of code okay so let's save this file let's go into here and let's import this DB which I have created now the error is gone and uh here we have this bcrypt which I will be using within this credentials provider and uh that's pretty much it we need to do for now in this particular file so let's close this db. TS file and first of all let's go over here in our Au rjs and let's click on authentication uh let's click on the database Prisma and we have already installed these packages we need to create this database URL in our EnV file so let's open that up uh let's add it over here I'll be modifying its value once I'll be creating a new database URL in my mongod DB uh Atlas actually and currently it is giving me the postest URL but I'll be using mongod d so let's come down I've already added this au. TS thing and we have this mongodb so it is giving us uh this pre-build schema models uh for our user authentication for the account for user for session management verification authenticator so for now I'm going to be copy pasting it uh from here well first of all I need to generate the Prisma so for generating that I'm going to come in the terminal and I'm going to write npx Prisma in it okay so let's hit enter and now you can see that uh it has this EnV file uh if you didn't create this EnV file it would have created this automatically for us and added these variables since we already had that uh compare uh let's click on that all right so now uh we have this Pres PMA folder automatically generated inside this Prisma folder we have this schema. Prisma file okay and we have this generator for the client provider Prisma client JS and then we have the data source data source have the postest which we can actually modify so let's modify that we have to change it to mongod DB this is the database URL which is added over here make sure uh there is no spelling mistake between the key name and we have this Prisma client JS all right so now here I'm going to copy models from the user all the way down until this thing okay so let's add it so you can see that we have uh this these models already added one thing more I would like to add is the user role if you want to implement user role we can have an enum user role and then we can have an admin and then the user okay and to make it uh relevant to the user we can uh add it over here so let's add role user role this is going to be an optional and the default is going to be admin because the two Valu VI are supported by this user role inum so I've added this over here so we are actually configuring the schema and we don't need to modify that some of its uh uh keys or you can say the properties are not required for this particular video for but for down the road uh you might need all of these uh things for implementing uh authenticator to FAA or the forget reset password so I'm going to to keep all of these properties in my schema all right so let's close that we have this database URL uh now finally what we need to do is we need to connect the real database URL over here and after that I'm going to be generating and pushing my database schema to my mongodb database okay make sure you save all of these things and also U I'll come back to this um let me quickly add these variables so we don't forget these later on we need to add these GitHub ID and GitHub secret uh after creating a new app in our GitHub uh settings profile settings okay so now I'm going to go to the mongodb and I'm going to click on uh this organization and here I'm going to be creating a new project so let's uh let's click on the atlas so in this organization I have this project already created I'm going to be creating a new project for you guys so you can learn everything from scratch so I'm going to be writing aujs V5 and let's click on next we don't need to add the tags which is optional and we are the project owner I can invite some new members so I can click on the create project okay so for creating a new DB make sure you go to the cloud. b.com sign up with any of your email ID and after that you need to create an organization and inside the organization you need to create a new project so this is what I'm doing over here I've already created multiple videos on setting up mongodb and which I'm doing again in this video for you guys so here we have this project created within that organization and inside it we need to create a new cluster by clicking on Create and I'm going to go with the free let's leave it like this cluster zero and uh I'm going to be choosing my nearest region which is going to be this one you can choose any nearest region uh you by selecting it from here and uh we don't need to do anything else let's click on the create deployment so it is going to take some time and it's going to generate the cluster for us so you can see that it has generated and we have this uh username and the password make sure you save these passwords and the US username uh for for future to be used and uh let's copy this one and let's click on the create database user which I have just created choose Mongo's method let's click on the drivers and we have already installed mongodb we don't need to install it again and we have this URL let's copy this URL let's click on the EnV and let's replace this whole URL with this one one thing which we need to modify in this URL is is the DB name which we need to add so let's scroll to the right before this question mark we can write the DB so Au next V5 and this is the DB name I have written you can write anything over here uh we don't need to do anything else all right so now in our terminal I can actually let's let's click on the done and let's click on the database currently it won't show anything let's click on the browse collections so it is actually retrieving the list of data So currently there is no data that's why it is showing this now if I go to the Prisma let's go down so it is asking us to apply the schema and the generate the Prisma client so these commands does not work with the mongod DB these commands work with the mySQL database so I'm going to show you the commands which are relevant to mongodb but if you are using postest database you can still use these commands to actually apply or the generate so I'm going to come over here in the terminal and I'm going to run npx Prisma generate first of all and it has been generated without any error okay you can see and now I'm going to create npx Prisma DB push let's hit enter so it is going to go through the URL of the database which we have actually added over here and now it is not showing any error so I'm hoping that it is going to generate all of the schema models which we have added over here and it's going to be adding over here um I hope that it's going to generate and we don't need to create a new user for that and yes you can see that it has added all the models in our mongod B uh by just running that particular push command account authenticator session user verification token and this is the datab based name Au next V5 and this is what we added over here in this particular URL all right so our configuration for the Prisma is working pretty fine and now it's time to implement uh login with GitHub um uh so let's first configure that I'm going to open up my GitHub profile so here I need to go to the settings of my GitHub profile in fact if I go to the au. JS Prisma let's go at the top authentication credentials database uh we have this web o in o o yes and after clicking on o o we can click on GitHub and how to set up sign in with GitHub so this is how it is recommending us stuff so after going to the settings we need to click on the developer settings let's go down developer settings and here we need to click on o o apps this is what it is suggesting and we need to create a new oo app okay so let's click on that I've already created this one now I'm going to create a new one for you guys so let's add the Au V5 and the homepage URL let's go what it is providing so we need to add the Local Host uh this one let's copy it let's paste it we don't need to add the description this is optional and authorization call back URL let's click on that so this is what uh is provided by this documentation you need to add this and uh now for production it will be with the https with the proper domain name but for local uh it can be this uh this one okay so after that I'm going to click on the register application and then it is going to provide me this client ID let's copy it let's paste it over GitHub ID and then we need to generate a new secret I'm not going to show you uh but I'm going to copy the secret and add it in my EnV file and you can see that we already added these Au GitHub ID and Au GitHub secret which are coming from the EnV file before I forget to put this EnV file in git ignore uh let's actually open this up and I'm going to add it over here so it doesn't get included in our uh git commands to push it in our repository okay so let's close it and now we need to create the UI to actually log in with the GitHub for now and I'm going to do that next so first of all I'm going to set up the layout of the whole application currently you can see that it is aligned on the top left corner which is not looking good I'm going to set up a proper margin on left and right and top uh and move everything in the center of the page okay so first of all in the global I'm going to remove everything which is added inside but keep these three lines because because without it we cannot write Tailwind CSS and here I'm simply going to write uh background color and this is going to be gray so I'm going to be adding 1 d 1 D and then I'm going to Simply change the color of all the texts to White okay so this is how it's looking now which is gray and the white text let's close this global. CSS and inside the layout I'm going to first of all set up the layout for all the children and here I'm going to wrap everything within this div and then let's add the class name let's add MX Auto Max width screen large height equals to screen flex and the flex column okay and inside this particular div I'm going to add another Dev and this is going to take all the children let's add a flex grow class let's remove the children from outside and above this children div I'm going to load a nav bar which I have yet need to create okay uh but for for whole session of the user which is logged in to be accessible in the all the routes uh so that we should be able to know that whether user is logged in or not and get the user information in all the files and folder of this app directory we need to wrap this whole HTML within a session provider session provider is uh given by next a uh react and then we need to provide it s session session can be fetched from uh the .js file which we have created so let me first wrap it around the HTML and this session needs to come from Au so session equals to await o at/ okay and let's add async because we are using a wait all right uh let me verify session provider is fetch from next o react and Au yes that is fine now I'm going to create this Navar first of all let's add this page. TSX and I'm simply going to add a text this is going to be a default text over here all right there must be some error about the nav bar so I'm going to add a new folder components and inside the components I'm going to add a new file this is going to be the navb bar. DSX RFC and this is going to show the nav bar above the children there should not be any error now let's refresh actually we need to import that which we have created fix and this is the nav bar all right so let's save it and now you can see that these are all the ch run and this is the nav bar this is containing only text for now and which we are going to modify now so inside this Navar I'm going to create first of all the logo and for now we can simply add uh a text for the logo so let's start off with a nav tag and inside the nav let's start off with the div and inside this div let's write link from next link this is going to take the class name and I'm going to add the flex uh not for the link but link is going to be simply font bold and href is going to be the slash so this is going to take us to the Home Route all right and inside the nav I'm going to add class and I'm going to add the Border bottom background BG background we can have width full Flex items Center and inside this div I'm going to add class name this is going to be the flex with full items Center justify between and margin to the Y AIS equals to the four let's see yes you can see that we have this home and we have this border at the bottom you can change the color of it if you want and below this link I'm going to add another div and inside this div I can add these links two links actually one is uh the middleware route this which I yet need to create uh and rather than href I can have the name of this route is middleware the reason I have given it the middleware name because I will be protecting this middleware route from the middleware file and the next is going to be this server the reason I've given it the name server because I will be protecting it directly within the server component but not from the middleware fire so I'm going to be showing you uh different ways of protecting routes and giving it the same name over here okay so server and we don't need uh these classes over here let's remove that and for this diff I'm simply going to add Flex item Center and within this I'm going to giving it Gap X5 okay and yes you can see that it has this middleware and the server routes which are not existing yet I will be creating it uh once I test the login with GitHub functionality so after this div I'm simply going to be adding this div another div for the login log out buttons so I'm going to be adding Flex items Center and the Gap X5 okay and inside this I'm simply going to be navigating us to the sign in route signin route will be automatically triggered uh uh over here which we have yet to create so inside this div I'm going to add let me copy this link and rather than href I'm going to add the signin and inside this link I'm going to add a div inside this div let's add this login and now you can see that there is a space in between all of these div sections uh I have get to add some styles to it so let's add BG blue 600 text white text SM PX4 py2 rounded sm all right so you can see that it is looking pretty good and if I click on it I should be navigating to the sign in route which I'm going to create now uh so I I don't need to do anything over here now so for now I'm going to Simply close that and here inside this app directory I'm going to create a new folder and this is going to be the sign in folder let's create a new file and this is going to be the page. DSX page and uh this file is going to take up the form for the login and also a button for login with GitHub so for this particular Dev I'm simply going to add a class width equals to full Flex mt20 justify Center all right so now inside this div we can have a section class name this is going to be the Flex Flex column and withd 400 pixels all right so within this section I'm going to add an H1 for the sign in uh the title at the top and after that I'm going to be loading login form so let me add uh to do login form for let me comment this line which I will be doing and next thing is login GitHub which I yet need to create uh so for this H1 I'm simply going to add a class and this is going to be the text 3XL with full text Center font bold margin bottom equals to six all right so let me copy the name of this component over here and login with GitHub let me quickly add this component so let's copy it over here so login GitHub do TSX all right so inside this I'm simply going to create a button so rafc login GitHub and inside this div I'm going to add fa GitHub and this is going to be coming from the react icons so GitHub like this let's give it a class name text white I want icon to be of white color and then let's add a P tag login with GitHub over here so inside this div I'm going to add this class name so to save over time I'm simply going to add different classes because the purpose of this video is not to teach you uh the Tailwind CSS but these are few classes which I have added so here let me click on the login there is an error obviously we need to import that over here uh This One login with GitHub let's save it and now you can see that we have this title sign in and then we have this component loading up which has this button over here and uh for clicking on this button I'm simply going to create an action action in nextjs are called the server actions uh which we can use to perform any DB operations so in short words you can call server actions as the apis okay so I can create any folder anywhere but to structure it properly I'm going to create an actions folder outside uh at the root directory of this project and inside this I can name uh the file all au. TS so uh this particular file is going to be containing all the server action functions related to authentications only that's why I've given it a name au. TS so let me create a new function login async provider string like this and now I'm going to write the sign in sign in is going to be coming from next Au react which is the built-in function provided by au. JS to login with any provider so I'm going to pass the provider so once the login is successful with the GitHub or any other provider I'm making this function as Dynamic from the client side from the components whether rendered from server side or the client side I'm going to pass the GitHub Google Facebook or any other provider uh which is going to be used to login a user with okay and once the successful login is done I'm going to redirect it to Home Route okay once the login is successful I want to revalidate path from next cache the Home Route sometimes when the login happens then we have to revalidate path so that everything uh is synced properly okay uh so we have this sign in we have this revalidate path uh I'll come back to this because I will be adding login with credentials log out let me add the log out uh thing as well so I'm going to add export cost uh log out await sign out revalidate path yes but sign out needs to be fetched from the uh this one this one actually sign in I have fetched it from here sign in can be used from this at o as well okay if I show you this o I am actually exporting sign in sign out and O this is something which we can use anywhere in our server actions all right so this is the function which we need to call to log out this is the function which we need to uh login with any provider any social provider actually okay uh so once the sign out is complete I can also pass the redirect to this route as well all right so let's go over here in our login GitHub and here I can actually add an onclick event so on click and here I can write the login from the the actions and let's pass it to GitHub all right so let's go over here let's refresh there seems some kind of error so we have this onclick so we need to make it use client because it require user interaction okay and for the server actions we don't need to write any actually this is the server action uh so anything which is happening on the the server that is accessing the DB we can write use server at the top all right so let's go over here you can see there is no error if I click on the login now let's see what happens all right so we are successfully navigating to the GitHub page for authorization um and uh before actually making it authorized let me go over here in the nav bar so that I should be able to log out as well otherwise I will not be able to log out uh let's let's okay there seems an error let's save it all right so in the nav bar um I'm going to show the log out button as well so inside this particular Dev uh first of all I'm going to make a check that if user is logged in or not so to make a check I can actually fetch from the Au this o is going to be coming from at o this is going to be uh async all right and uh this session is going to give us a clue whether user is logged in or not so inside this particular div I can write if session. user does not exist it means that user is not logged in okay so I can put this login button inside this all right so once if user is logged in then I'm going to show the email of the user maybe the image of the user uh or and the log out button as well so I'm going to create a new component for the log out which is not yet created uh so let's do that quickly I'm going to go over here and I'm going to write log out. TSX and inside it I'm simply going to add a component directly I don't want to waste time on that so this is uh you can see this is the use client because it require on click we have this log out action which we have already added in .ts log out and uh then we have this on click calling this log out and we have this simple tailin CSS with this log out link okay so let me save it let's close it let's go onto the navbar let's bring it in and there is this thing so all right so now I'm going to also show some kind of uh div for actually showing the user email and the image let's first add Flex items Center Gap X2 text SM okay and inside this div I can add the session. user.name and also I can actually write the session. user. image okay if image exists we need to get actually it provides a URL so we need to show the image in uh as a URL so I'm simply going to add an image over here image needs to be fetched from uh let me import that manually from next image so import image from next image all right so let's go over here let's go back let's refresh this page and let's we are already on the login page and let's click on the login with GitHub and now let's authorize we need to authorize it first time because we are logging in with the GitHub and uh the GitHub email ID you must have got a notification on your email address that uh the third party oath app is trying to access your account so currently uh inv valid source prop uh actually we need to add a host uh I hope that you already aware of if you have been learning a nextjs then in our next config we have to add the images and then the domain so images and then the domains GitHub user content let's see let's refresh we have yes all right so you can see that uh I'm able to see my name and my avatar from the GitHub and also the log out button because I am logged in all right and now if I click on the log out you will see that I able to log out perfectly fine and because of the session of the user I can see this login button and I can see that name Avatar and the log out button uh after logging in with the GitHub let's try it again I have clicked on this login with GitHub and it should uh automatically log in rather than letting me authorize it again so yes so it didn't ask me to authorize it again and I can see this uh login and then the log out all right so let's click on that next thing I'm going to do is uh I'm going to actually protect these routes quickly once the protection is done I'm also going to show you how we can access the uh session user details in our apis as well in next JS and after that I'm going to come back to this login form uh for login with credential and the user registration as well by the way if you open up the mongodb database uh and click on this refresh button you will see that the entry for this user is going to be added in our database against the relevant models since we already tried login with GitHub from our application and if I click on the authenticator the relevant model will have the details I can click on the user uh user should have the details yes we have these details and we have the Account Details account is for the oo uh login providers uh so these two models have these details uh I think if I'm going to log in with credentials this session is going to be having the data as well these models are for the global perspective as I've told you earlier that uh we might need to add forget reset password to fa and all of these these things that's why the documentation have provided uh the model schema for all of these purposes okay so let's come back over here and this is the app running if I click on the Middle where this route does not exist so it is going to show me this default uh 404 error okay so I'm going to create this particular route I'm going to right click app click on the folder and here first of all let's add the Middle with here inside it I'm going to add page. TSX so let's write R fce middleware and inside it in order to F the details of the logged in user I can write session equals to the await o Au is going to be coming from at AU let's add async and we have this session okay so I'm simply going to add some uh UI over here the Tailwind CSS so let's add it over here so we have this main Dave middleware page and the session. user. email uh the loged in user email is going to be shown over here this is not going to be you can see it is showing the title but not the email because I'm not logged in I will be protecting this route from the middleware file uh rather than directly in this particular component uh so so before that let's quickly create another folder server and this is the route which I'll be protecting directly from within this file okay so page. TSX I'm simply going to copy paste everything from the middleware and I'm going to change uh the name of this component to server okay and using this session I can actually red IR since this is from the server site I can use uh if session dot question mark. user does not exist then I can simply redirect it to the Home Route redirect can be uh from the next navigation so next navigation all right so now if I click on the server you will see that I'm not able to navigate to the server because it is protected now let's try to log in with GitHub again and now I will be able to navigate to the server and I should see the details let's click on the server and now you can see that uh the email is visible middleware have this email visible let me change the title for the server page yes all right so middleware server let's read refresh actually yes you can see that this is the server page showing the email uh and I can actually access this particular route it is no more protected now let's quickly protect our middleware route from the middleware file so middleware dots file so in this particular file this line I copied from the documentation I'm just going to comment that uh I don't need that uh for now so import let's add uh o from at o like this okay and now I need to export default async function middleware request column next request from next server and uh I will also be needing next response from here all right so I'm going to Define an array that which routes I want to protect actually I can directly write it inside this middleware as well um like this um so return next response next to avoid any kind of error so above that I'm simply going to ADD protected routes so this is where I'm going to Define all the routes for now I'm simply going to protect the middle Weare route okay now let's use this array to actually protect this inside this middleware so let's add this session equals to weit O and uh now is protected equals to protected routes sum route and request next URL path name starts with route this is looking good now we have this not session is protected I'm I'm going to modify this so const absolute URL equals to new URL this one request next url. origin and after that uh redirect to the absolute URL do2 string all right uh one last thing I need to export from here is the config me Mater okay and if I go to the protection protecting part of ar.js I need to copy this particular matcher from here now let's save this file and I'm going to go and let's refresh it and it's not actually loading let's go over here so one thing that I would like to do is I'm simply going to remove move next request from here let's copy it let's paste it and next request import type next request and also this condition was selected by the extension which I'm using I didn't see it carefully so I can actually change it to and and need to remove this not operator from is protected so let's save it now and let's go let's refresh there is no error I can actually navigate to the middleware and the server routes because I'm logged in let's click on the log out now and click on the middleware I cannot actually navigate to the middleware because of this particular condition which I have added and I cannot navigate to the server because the server route is being protected directly within this particular component over here okay uh so you can ignore it for now next time it will not be shown up all right so now next thing I want to show in nextjs we can have apis as well so let's create a smallest API within this API route so inside this API I can actually have another folder let's give it the data let's add a new file and this is going to be the route. TS so inside this I can actually import uh next response from next server and let's export const get equals to and to actually protect our API routes I need to wrap the whole function of that API within the AU from that Au function which is being returned from Au file which we have created and inside it I can have it like get request and this so if now I can actually detect if user is logged in or not so I can have request. o and then I can actually return next response. Json request. o okay if user is not logged in then I'm going to Simply return uh the next response. Json and rather than sending the user I can simply return a message that not authenticated okay and along with that I can also pass the status 401 so let's save it let's go over here and in order to navigate to that API I can actually call like API SL dat now you can see that it is showing the message not authenticated let's go back because I'm not logged in let's try to click on the login with GitHub and try to log in and once I'm logged in I'm also going to navigate to that/ API SL dat route and now you can see that it is giving me a proper detail of the user this is what I am returning it from here and it is giving us uh the correct results so using next o session object wrapping everything within the Au I can actually fetch the data of that user or anything I want to do based upon if user is logged in or not so one thing uh left for this particular part of the tutorial is uh login with credentials which I'm going to be adding right below this title and login with credential and also user registration during the login process so let's do that so here in the signin page I added this to do I need to create a form over here rather than directly creating form inside it I'm going to create a new component so right below this sign in title okay so let's remove this comment and I'm going to add login form as a component so let's create that so inside this components folder I'm going to create a new file and this is going to be the login form. TSX so let's add rafc let's save this file and also let's import it from here all right so now I'm going to go to the login form and here I'm going to start off creating that form so first of all let's add a div and inside this div I'm going to create a form inside this form I'm going to create another Dev okay so first of all this form is going to take an action which I'm not going to add anything for now after that let's add some classes so width full Flex Flex column Gap equals to 4 for now let's remove the actions because of the error and uh this is going to be the dev div does not need any styling uh so inside this div we can have a label so label is going to be email below this label we can have an input type email placeholder email and I also want to add ID of email and I want to add some classes okay so rather than actually wasting our time let me quickly add some styling to it so these are some classes added and for the label I'm also going to add a few classes directly copying it okay blog text SM uh let me see you can see that it's looking pretty good email and then this email um and now we don't need to add any class to it as well so now let's copy this div paste it below and add it password type is going to be the password email uh placeholder is also going to be the password ID password and the class names are going to be the same okay so and also one important thing is this name name is very important because without name we will not be able to pass uh the values inside these input uh to our server action which I yet need to create inside it uh this is going to be a function to login with credentials okay so for email as well I'm going to add name okay uh so now below this form let's go over here it's looking good and below this particular div I'm going to add another div and this is going to take Au buttons the reason for the button I'm creating a a separate component because I want to use use form state lus hook to actually show the loader during the process of the login because it has to be the child component uh for uh having that use form status uh in in a proper working condition okay so now mt4 let's quickly add that Au button. TSX okay so let's add our fce and inside it I'm simply going to import pending State uh equals to use form status from react Dom and inside this return I'm simply going to add a button so for this let's disable that if it is pending during the process of the login I want to disable it and I want to give it the type equals to submit and after that I'm also want to uh so for for the content I'm going to add if it is pending then I need to show uh loading otherwise it is going to be the sign in okay and for the classes class name I will be uh adding the class name directly over here without wasting time so let's add that so now you can see that if it is pending then the background color is going to be gray otherwise the button background color is going to be blue uh and these are some default styling for the login button and the text is also going to be changed if it is pending it's going to be loading otherwise it is going to be the sign in in all right so let's close that and let's bring that in so Au button all right so let's save it uh there seems some kind of uh error you are importing a component that needs use form status it only works in the client component actually uh I actually this is the login form and I want to I need to actually change it to use client okay so now you can see that it's looking pretty good we have this blue button and if I click on this uh button it will not do anything uh practically on the back end uh so let's do that now so in the inside this form uh I would like to add a function over here inside this particular file so this is going to be a server action so export const login with ceds equals to the async and I'm also going to pause the form data which is going to be of type form data const like this okay so let's pass that out so I can actually pass this data out so raw form data equals to I'm building it uh as an object okay so this is going to be an email form data get email as a string get password as a string and now I will also be passing an admin I'm not passing it from the component this is just a random thing I can actually pass some parameter from here and then add it over here but this is just for you guys to understand we can actually set up the role as well at the start of the video I modified the schema which I copied from the documentation uh to add the admin and the user roles and then I'm going to add the redirect rules redirect to this one so once we compile this data over here actually we don't need this as string over here um after that we can pass it to the credentials provider in the au. TS and process the login but uh before that I've actually added this particular function uh this is actually for debugging purpose whether the login is successful or not and this is also going to detect that uh if the user with this email exist in the DB or not so here in this function I'm passing an email ID let me let me do that so this one as string okay uh because this is of type string this DB is this DB which I have created using the Prisma this is where I'm exporting it and uh now this user uh is the model name the schema model name find unique is the built-in function of the each model that we create in Prisma where email ID this is going tock check if the email ID which is being passed over here is actually exist in the DB or not if yes it is going to return a user otherwise it is going to return null okay so for now I'm going to Simply log that existing user okay uh next what we can do is we can process the login functionality so I'm going to add the tri block and inside it I can use the same signin function which I used used for the GitHub login credentials like over here sign in this is not required by the way I've just added it for debugging purpose okay so this is the name of the credentials which I need to uh accept over here in the credentials provider and raw data is being passed uh which I have compiled over here okay and uh let's move further now we don't need to receive it in the user and inside the catch block I have this error of type any okay and uh then inside this catch I can check if what is the status of the error using this Au error which is provided by the next o Au error gives us some error types like the credential sign in we can uh return some default custom error message from here otherwise in the default in case something went wrong will be returned finally just like we did over here revalidate path uh we can add it over here all right so this is where we have done it now we need to call this login with Credence uh over here inside this form once it is submitted so action equals to login with credits okay all right so that is done now once this form is going to be submitted this is going to be processing uh this form and this is where it is going to receive and whenever this line is going to gets executed uh we are going to receive this raw form data over here within this credentials provider and this is where I'm going to write some further code to process the login user registration error handling and more so first of all in this credentials I'm going to start start off with the name and name is going to be the credentials okay so after that let's add these credentials first of all we have this username we don't need username we have the email email is going to have the label this is going to be of type email and we can have the uh placeholder as well if we want uh like this okay and then the password is going to have this label and the type is going to be the password okay so after this credentials object what we can do is uh we have uh this async authorized credentials uh function okay so but I'm going to write authorize colon async credentials Arrow function okay so inside this uh first of all I'm going to check if not credentials or credentials. email if any of these does not exist then I'm simply going to return null next I'm going to receive the email ID and then the password from that server action so email equals to the credentials. email as string and then I'm going to Hash the password hashing the password actually uh is important for the security purpose we don't want to store the user password directly in the database uh we want to encrypt that password okay so const hash and let's create a new utils folder inside did I'm going to add helper. TS file and this file is going to take a function using the bcpt GS package I've just copied it uh from its documentation uh with slight modification you can just pause the video and write it down yourself uh so let's close it and here in the au. TS I can write the salt hash and then I can pass this particular password inside it to process uh the password hashing okay so once that is done we don't need to pass it as a string to it okay so next I'm going to check if user of type any equals to await DB do user doind unique where email okay and the reason I'm checking it over here to actually address if user already exist in the database then I don't want to register a new user in the database and if it is does not exist then first I will be registering it in the database then I'm going to process the login functionality okay uh so login is already done uh uh over here this is just to process the registration and the login stuff so if user does not exist then I'm going to uh add a wait DB user create and then data this is going to take an email and uh we can actually add hashed password and then the hash okay I'll come back to this uh it's not a very big error so if user exists then I'm simply going to uh process the login by uh compare the syncing if the password which is stored in the database uh is actually matching with the password which is passed from the form which user is trying to login with okay so I can try as match equals to bcrypt do compare sync credentials. password as string with user. hased password okay so now after this I can check if this does not match then I can simply throw an error that incorrect password okay but after this I'm simply going to return a user returning user means that we are successfully processing the login process okay uh so let me go up and uh let me try to fix this error as we know that this data contains the key value pairs which should be matching with the schema which we have created so we are using the users schema so let's open up the schema. Prisma this is the user schema which we are using so uh we are actually passing the email which is correct um and we don't have the hashed password over here which we are passing over here so we need to add that over here so I'm going to add hashed password and then the string so let's sa it it will not work quickly what we need to do is we need to run those commands to regenerate that schema so in the terminal I'm going to run that command again so npx Prisma generate now you can see that the error is gone locally it is generated now we need to push it in the DB as well so npx Prisma DB push all right so this new uh variable is going to be pushed so whenever you want any kind of modification in your Prisma or or the schema models you need to run these two commands when you are using mongodb uh if you want if you are using mySQL database then the documentation of the ar.js have have these commands which you can run okay so let's close that and this error is gone now there is no error in this file so let me run the project now so the project is running let let's go first of all let's refresh this DB and uh I want to verify the user there is no data over here it's still loading So currently uh it's showing some kind of uh data the reason is that uh we have uh used this particular email ID for login with GitHub okay and uh we have this session authenticator and the verification token uh account will also be be showing the same email ID which I used to log in with the GitHub U so I will be using a different email ID so let's go over here uh let's refresh this page so this is the form uh and let me uh add a new password so capital A B C D 1 2 3 4 so this is the password I have just added let's click on the sign in now so it's showing loading because of the use form status all right so let's click on update password and it is showing the log out button it means that we have successfully logged in but it's not showing that Avatar or the email uh which I need to see but let's go over here let's refresh and see if the user with the new email ID exist over here in the user model or not uh it should be added yes you can see that this is the email ID along with the hashed password with the role uh here it has added over here so over um user registration is successfully being done and here uh let's click on the middleware and we are successfully logging in and if I refresh this page uh we cannot see that uh Circle over here which I need to see so let's go over here in the Navar and session. user. name and then the image uh do I have uh an image or an email actually we don't have an name or email uh while logging in we did not pass the username so while fetching the user data you can see that here we had this image but here we don't have the image all right image is optional in our schema and also we have this name property but here we don't have the name property this is the reason that details are not being shown up um and uh we have seen uh the login with credential successfully working along with the user registration and also while we are logging with the credentials the protection of routes is also working fine um the same configuration is working that was working before with the login with GitHub if I click on the log out I'm not able to navigate to any of these routes okay guys thank you so much for watching let me know in the comments of this video if you want me to further create more parts of OJs version 5 to add forget reset password feature although I've already created a video using the previous version but if you want me to process from this step further to add the forget and reset password and also I'm will be happy to assist you guys with the two Factor authentication as well in this part particular so it will require couple of more parts let me know in the comments of this video and do like my video as well it will really encourage me to make those extra parts of this tutorial OJs Varian 5 so thank you so much for watching guys again see you in the next video where I will be talking about uh more stuff in nextjs 14 or 15 or let me know in the comments below see you in the next video
Info
Channel: Programming with Umair
Views: 2,999
Rating: undefined out of 5
Keywords: auth.js v5 nextjs, next auth v5, next auth tutorial, next auth with prisma, next auth with mongodb, next auth, auth.js, next js tutorial, authentication in next.js, login signup in next.js, next auth next.js tutorial, auth.js v5 guide 2024, authorisation in next.js, routes protection in next.js, next.js 15 tutorial, how to create next.js 15 project
Id: sQ3fPyko6o8
Channel Id: undefined
Length: 82min 52sec (4972 seconds)
Published: Mon Jun 24 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.