Auth and Private Routes Next.js 13 | Mongodb & Next Auth Credentials

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video covers sign up sign in sign out private route guest route and the admin route using next year's next auth and mongodb first of all I'll create this brand new project I will go with all the default options and this is how it looks now we need the UI I don't want to waste your time creating UI so I asked chat jbd for that and these are the UI that I got next I built a simple Napa with basic menu items but the main thing about this menu is this auth menu component because it changes UI according to the user's authentication status for now we'll just use this hard-coded value and welcome to this component later now let's start to build our auth system let's install few packages that we want we'll use Mongoose to handle our database next all to handle authentication and this big clip will help us to Hash our users password also we need the types for this big clip now let's try to connect to our database for that I'll clean and add this DB file inside this directory called leave let's import Mongoose and grab the database URL from the environment variable and make sure to create this dot EnV file inside your root directory and add your database URL then I'll add the variable called connection just wait to find out why we are using this variable then we'll create and Export this function called start DB now inside this function we want to start our database so we'll check if there is no connection then we want to connect to our database using this Mongoose dot connect method adding this if condition will prevent multiple DB creation request and that's it for database connection to create user model I'll create a folder models and a file called user model before we move further let me explain what we need here first we need to store our users information like name email and password and because password is a sensitive thing well first has the password before we store it and because we are going to have this password will also need the method to compare the password later whenever we want to sign in so for that we have installed this package is called big grip now let's import all the necessary things that we will need then I'll add this interface called user document where we'll Define the things that we want to create our user like name email password and the role for our users and there will be two different roles admin and the user also I'll add this interface called Methods where we will have our compare password method which will take the user's password and return the Boolean value which will Implement later now let's use all these types and construct our new user schema first of all we'll need this email which is going to be type string this is going to be require field and email needs to be unique for every user then we'll do the same thing for this name but this time this doesn't needs to be unique but whenever we want to save this we will trim its value and at the end we have this password which is going to be a string and this is going to be a requirement now here comes the role which is going to be string and this can be only admin or user and default is going to be just user then finally we are going to has our user's password before we are going to save them but we don't want to ask the password all the time we'll do this only if we are modifying the password if not then we are simply going to call this next function and we'll simply has the password and assign this to our this dot password and call the next function but to Hash the password we'll need the salt which we can create with this big clip.generated salt where you can pass the salt run and that's it this is how we are going to Hash our user's password now because here we are using the async and avoid things can go wrong that's why here I'm wrapping things inside the strikes blog if there is any error we'll simply throw this error now we want the compare method which we can create with this user schema methods compare password which is going to be the same exact function now from here we have to return the Boolean value which we can do with this big dot compare method where we can pass the password coming from our user with this user's password again because we are using the amazing and await yeah I'm going to wrap everything inside the strike catch at the end we can create our user model but for this one we have to first of all check if there is already this user model inside our models otherwise we are going to create the new user with this user schema and finally we can export our user model by casting its type and now it's time to handle the sign up for that we have to create a route inside this app create this folder called API auth users and inside here will create this route.ts and there's the new way to add EPA routes inside next.js13 even though this API folder is not needed we are going to use it first of all I'll add these two interface called new user request and the new user response inside this new user request will have the name email and the password which is going to come from Insider fronting then inside this new user response we will add the data that we want to send as the response which is going to be ID name email and the rule then we have to create and Export this function called post which is going to take take this request and it will return This Promise with this new response and this new response is going to be your next response where you can either return your user or you can return this error also you can tweak this according to your need now we want the data coming from front end for that we can simply await for this request.json and cast its type to new user request which is going to give us everything inside this body then obviously we have to start a database because we want to access our database after starting the DB we can simply check if we already have this user inside our database if that's the case then we want to send the error response email is already in use with the status 422 otherwise we'll create our new user with this user model dot create method where we can simply spread our body where we'll have name email and the password and once we create the user we can simply send the Json response with this brand new user where we'll have ID email name and the rule and that's it now this is your sign up and now I'll open my sign up page and here we are going to handle our user's name email and password because we want to handle some change events we have to mark this as our client component we are updating the user's information inside this handle change and here we have this handle submit which is right now empty and we have these three input Fields where we are handling name email and the password and now if we use the button to submit this form thus handle submit will fire now here we already have this event so let's first prevent the default Behavior then we can use the feature API to send request to our API or slash user which is going to send the request to the method that we built earlier so method is going to be post and body is going to be user info but we have to stringify the value then if we got the response we want to use this rage.json which will give us the response which we can simply log to our console and that's it that's how we can send requests to our API and now I'll visit this localhost 3000 last auth sign up and this is the form that I have and now if I fill this form and sign up then I'll get this response inside my console where we'll have email ID name and the role for this user also if you want to fix some user experience you can simply create this state called busy which you can update inside your handle submit and whenever you are going to be in the busiest State you can disable the button and also you can change the style according to your need and now if we submit this form again that's what we will get now the next will handle the sign in route for that we need to create this special folder inside this API auth and the folder name will be triple dot next or which we have to wrap inside these square brackets and then we'll create this file called route.ts inside this route.ts first of all we'll create this auth option which is going to be next auth options we'll add these options later but for now let's create our auth Handler which we can do with this next all where we can simply pass our odd options and after this we have to export these two functions gate and post or we can also do something like this I'll use the second one because we have the same thing inside documentation as well and now it's time to add our auth options first of all we'll handle this session and here we have to pass the strategy and there are two different strategies database and the JWT we will use this jw1 after session we have to pass the providers and there are a bunch of providers which you can choose but we are using email and password so we'll go with this credential providers where you have to pass the type which is going to be credentials and the credential itself but here we'll just use the empty object because this is going to create the UI and we don't want the default UI after this credentials here we have to pass the authorize function where you will get your credentials and the request object and this credentials is going to come from inside this object so this is going to be empty for typescript but we can simply really cast its time and grab the email and password now once we have our email and password we can simply import our star DB and call this function to connect to our database and once we connect to our database we can import our user model and find one user with this given email ID and obviously if there is no user we also want to throw an error but if there is this user then first of all we want to compare their password and again if the password doesn't match we want to throw that same error otherwise this user is chain one so we can simply return the actual response which is going to be this user object so from here we'll return name email role of this user and the ID but even after returning all these things from here this response will not go to our front end now if you want the same exact user response inside your application you have to add this option callback where you can simply pass these two functions JWT and session and these functions will run the first time when we send this sign in request inside this JWT we are going to check if there is this user then we want to update the token where we'll assign the role of this user and the ID of this user and finally we can return the token from inside this function and like the same way from inside the station we are going to first of all check if there is this user then we want to add the ID and the role of this user and again from inside the session we have to return this session and that's it now your signing out is also red and now it's time to handle sign in from inside the front end part for that I'll open my sign in page and again this is same like our signup page but this time here we are only handling email and password so let's prevent the default Behavior inside this handle submit and here we are going to handle our form submission so for this one we have to import this function called sign in from inside the next auth react and because we are using the email and password Here we have to pass this option called credentials and as the second in options you can pass your email and password and here is another important thing that we can pass and this is going to be redirect false which will prevent the default redirect and we need this to render error message coming from inside our backend then we can simply check if there is any error inside a response we can simply update the error State and we can return the process right here for that obviously we have to create our error State like this if we don't have any error it means we are successfully signed in at that point of time I'm going to Simply use this router and I'm going to navigate this user to this page called profile and to use this router first of all we have to import this use router from inside next navigation and we can create a router like this and obviously to go to this profile page we also need to have the profile page and if you are wondering how I'm rendering this error I am using this alert component where we can simply pass the value and we are rendering it inside this D after all these things now we need to wrap our application inside the session provider make a session provider is a client component I'm going to create this new file called auth provider and here we will use the session provider and wrap the children inside this and now we can import our auth provider inside the root layout and wrap entire application and that's it but before we test this application we have to have this next or Secret inside our DOT ENB because we are using this JWT as the session strategy and after all these things we can simply navigate to our sign-in page and if we try to sign in with our email and password we will be inside this profile page also if you open your application and the cookie section then you will find all these cookies generated by next auth now let's handle the logout part to handle the sign out I'll come inside this auth profile menu and here we can import this use session now this is going to give us the session object from inside this we can restructure the data and the status this data will hold the user if user is successfully signing and the system is this can be authenticated loading or this can be unauthenticated so according to the different status you can render the different UI but if this user is authenticated we are going to Simply render the profile name and the logout button and inside this logout button we'll simply pass this function called sign up which we can import from next on slash react and now if you see here we have a logout button and if I click on this logout button I'll be logged out from inside this application which will render this sign in and the sign up button and now it's time to handle some private routes there are multiple ways to handle private routes but I'll show you the simplest one for example if I want to I can visit this profile screen even though I am logged out from inside this application so now let's use this special syntax to group our routes this is going to be private routes and I'll add my profile page inside this private route and will create a separate layout for this private route and here we can import this next server session from inside this next auth and we can simply await for for its result and here we have to pass our auth options which you can import from inside your next auth route and here you can check if there is no user inside the session then we are going to Simply redirect this user to our sign-in page and you can import this redirect from inside this next navigation otherwise we are going to render the children and now if you try to visit your profile page you will be inside the sign in page but now if I log in inside the application I can visit the profile page but I can also visit the sign up and the sign in page which is not a good thing so now let's group another route called guest routes and here we'll add our auth pages and then we'll create separate layout for the screw and again here we'll do all those things but this time we'll check for this session if there is the session we want to redirect this user to the profile page instead of these sign in and the sign up so this is going to be the guest route which only the unauthenticated user can visit and if you have any other routes you can simply create the folder and the pages inside is gazed routes and now if you are logged in and try to visit the sign up and the sign in you will be inside this profile page and now finally let's group the admin routes and inside this layout file again we'll have everything as the same but this time we will grab the user and check for their role if the role is equal to admin only then we want to render the children otherwise we'll simply redirect this user to the sign in page which will obviously redirect this user to the profile if the user is already logged in but if the user is admin then they can visit these Pages for example let's create this dashboard inside this admin group only if your role is admin which you can simply update from inside your database and using the mongodb compass and now if I visit the admin round I can visit if I am admin but if I log in with the different account and try to visit the admin I'll be inside this profile
Info
Channel: Full Stack Niraj
Views: 12,549
Rating: undefined out of 5
Keywords: next js, next js 13, next.js 13, next auth, app router, credentials, protected routes, nextauth 4
Id: 9fU8YL0jyIA
Channel Id: undefined
Length: 15min 53sec (953 seconds)
Published: Mon Jun 19 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.