Transcript for:
Next.js Password Reset Functionality Guide

hi guys welcome back to another video on next.js and i'm going to be covering up very important topic in this video called forget password and reset password functionality so even if you are using the variant 13 of next.js variant 14 or any new variant coming up in the future that uses app directory you can follow this video so i would say this is the second part of one of my previous video in the first video i have already covered the login user functionality registering new user functionality login with github functionality and building these forms navigating from login page to the register page and from registered page to the login page and also most importantly i'm managing the storage of user data if it is registered or if it is login with the github i'm storing the user data in the mongodb database so in case if you want to have some relationship with other data of your user you can have the user data stored in the database and also i have already explained in the first video that using the authorization authentication feature that we have implemented how we can protect our routes and this is the dashboard route which i have actually protected because i'm not logged in currently that's why i'm not able to navigate to the dashboard route this is what i have already explained let me show you my playlist of next.js 13 and next.js 14. and also show you the first version of this video. So this is my channel. If I go to you can go to the next just 14 tutorial playlist as well. And if I go to the playlist next year's 13 tutorial, you can see that I have created a lot of videos, almost 37 videos.

If you are using the version of next year's that uses app directory, you can still follow this playlist and it covers pretty much every topic for you to become a good next year's developer using the app. directory structure you can see that the best practices of use effect use hooks connecting with the mongodb theming server actions redux toolkit context api handling with the cms like the sanity or the ghost cms debugging building apps different ways to protect routes typescript in next js 14 this is the first video which i'm talking about next auth login register in next js 14 with mongodb login with credentials and the github this is what you need to watch if you have already seen that or if you already know how to handle login registration feature and storing the data in the mongodb you can start keep watching the second part of this video but i would recommend you to watch the first part first if you have not understanding uh don't have understanding of the login registration process mainly with the next auth library and you can see that i've already created videos on the e-commerce website building with next.js 14 blog application development seo how to upgrade from virgin 13 to 14 with couple of commands okay and i'm going to be showing you how i will be upgrading my project from 13 to 14 just now and if you want to learn how to process the authorization authentication in next.js 14 using clerk package i've already created its video and this one video contains login sign up and forget password functionality in single video using the clerk package you can watch this video and you can see that i'm putting a lot of effort creating these videos for you guys so it's just a request it will really encourage me to make more videos for you guys if you subscribe my channel right now and like this video So let me give you an overview of the forget password and the reset password functionality. First of all, I need to create a new user and register it so that it can be stored in the database.

But first of all, let me show you. So currently it shows the forget password, reset password here. So here I can enter an email ID and let me see what happens because this email ID is not yet registered in the database. so if i click on submit it will show me that user with this email id is not registered so you can see that it is fully validated and all the edge cases are handled in this video so now first of all i'm gonna go to the register page and register my user in the database so i'm going to be writing uh abcd1234 so i'll be clicking on the register so this user have been registered in the database let me go over there and click on the refresh and see if the user is added in the database yes it's added and you can see that the password is completely encrypted for the security purpose as well all right so let's go over here now i want to first of all let me log in here so i'm going to click on the login page and let me change the password abcd1234 and i'll be clicking on the sign in now you can see that i'm logged in with the same credentials using which i have actually registered a new user and now i'm able to navigate to the dashboard route because i'm registered and this is the email id which is being fetched from the database for the logged in user and i can navigate to the dashboard page now let's go to the logout a link and i'm gonna click on the login and now i'm going to show you how i have implemented the forget and reset password functionality let's click on the reset password here now i'm going to enter the email id which is registered in the database and oh so let me add it again so this is where so let me click on the submit now let's see what happens so it should navigate to the login page yes it has navigated to the login page we can actually add some kind of toast as well but that is something you guys know that how we can do it but i've already received an email id with a link so let me copy the link from my email id which i have received so i've copied the url from my email id which i have generated myself from the code and this is the url localhost colon 3000 slash reset password slash token okay but first of all let's go to the database let's refresh and here you will see that it will contain the reset token and reset expiry date as well this is for the security purpose and you can see that the complete functionality is working fine let me zoom in you can see reset token and when i will be resetting it the uh the password this is actually to handle if the user token which is added over here is actually valid or not or whether it is already expired or not okay so now i'm gonna be hitting this url let's hit that and it will take me to the reset password route now okay so here i will be entering a new password here so let me add a new password so i'll be adding a b c d one two three four five six okay so now let's click on the reset password now the password is reset and Let's go to the database and refresh this page and see what happens over here. And now you can see that the reset token and expiry date have been removed because it's not in the process for this particular user.

OK, so now I can actually log in. First of all, let's log in with the previous password. You can see that it contains eight letters, means it is containing the old password. Let's click on the sign in and invalid email or password because this. email and this password actually is not correct so i'm going to be adding the 456 at the end so let's click on the sign in and now you can see that if i go over here you can see that i'm able to log in with the new password so this is the functionality which i'll be implementing using next auth package in next.js 14 variant using the app directory all right so let's get started from the code base of the previous video in which i implemented the login and register functionality So I will be implementing forget reset password functionality from scratch.

You can see that there are no components, no files for forget reset passwords, no API routes for anything. So I'll be implementing everything, including the UI from scratch in this video. So this is the code base of the previous video. And I use the variant 13.5 for this video. There is no difference.

The folder structure, the app directory structure, how we create APIs, how we create routes. pretty much same okay so i'm quickly going to show you that how we can update the variant 13 to 14 with couple of commands okay so in the terminal first of all you need to update your node and npm variant which is the 20 in my system so i have actually checked 10 of npm version so now uh first of all you need to run this command npm i next at latest react at latest react dom at latest eslint config next at latest so it will update these packages from version 13 to 14 and also you need to update the typescript variant as well if you are using typescript but you don't need these couple of packages for if you are using the javascript so i am updating the add types slash react at latest add types slash react dom at latest okay so these two packages are updated as well if i go to the package.json you can see that the next variant have been updated to the version 14. So our project belongs to the Next.js version 14. Okay, so first of all, I'm going to be creating a new route for the forget password. So I'm going to write the app directory.

click on the new folder and i will be creating forget hyphen password okay so let's create a page file inside it so i'm going to be creating page dot tsx okay First, let me run the project so that I can keep on looking the changes which I'm making in terms of the UI. So it's running on localhost 3000. Let's go ahead and refresh. So here currently I will be navigating to forget password route.

that what it contains it will throw an error so what i'm going to do is i'm going to copy paste the code from the login component inside the forget password component to copy some kind of ui okay so most of these things i will be needing over here in this file as well it is a use client component because i'll be using the click handlers so i'll be needing these things here as well and i'll be needing this use effect i'm just going to show you that why we need it we need to protect our route and we need to use the use session hook to authenticate our forget password route so if user is logged in then we should not allow user to navigate to the forget password route it should only be navigated to forget get password route if user is not logged in okay i will be needing this valid email regular expression as well i don't need the password i only need the email from the form i'll be removing this if condition and i'll be removing everything from here i'll be implementing the handle submit after that okay so i'll be showing the loading when the session status equals to loading and here it is actually showing uh if the session status is not equals to authenticated and and after this I'm going to change the login to forget password okay so this is going to trigger the handle submit let's remove this password input element from here I don't need that so it is not actually text it is an email okay so this button is a submit so let's add the submit here change the text of the button and it will throw an error i'll be handling the errors based upon the response from the api the email does not exist in the database or if the email is invalid so I'll be showing the error messages over here alright and I don't need login with github on this page so let's remove it this is the button all right so let's remove it and let's navigate to the login page from here if user change the mind to not to reset the password okay so let's save it and I think we are done with the UI so let's go and manually try to navigate to the forget password route so I'm going to write the forget password hit enter and now you can see see that this UI have been successfully constructed and we can navigate to the login page from here as well all right so we have built the UI for it now what I'm going to do is I'm going to open up the login page and I need to add the forget password link from this form as well okay so I'm going to add it below this one I think I can add it above these input or you can add it below this form as well okay so i'm going to add that a div and inside this div i'm going to add a class name so let's add the text white text hyphen 16 pixels and margin bottom four all right so this has been added uh now i'm going to add forget password below this i'll be adding a link so this link is going to have a class name so class name will be having the margin left hyphen 2 text blue 500 hover underline Alright, so this has been added now. I need to add the href as well to it So for the href, I will be adding the forget password Okay, so let's save it and Inside this link. I will be simply adding the reset here.

Alright, so let's see How's it looking on the UI and you can see that it's looking like this over here and we can click on the reset password we can navigate to the login page from here so this is the ui it's working fine and now what i'm gonna do is i'm going to create an api route that will receive the data from this form and i'm going to send an email to a particular user okay and for that i will be using the service called sendgrid and i'm just going to show you that how we can configure sendgrid use its token to send the email id so let's create an api route by creating a new folder inside the api directory and i'm going to name it for get password and inside it i'm going to create a new file route.ts and to save some time i'm going to copy the code from the register API route and I'm going to paste it in the forget password API route okay so here it contains this bcrypt which I don't need so I'll be removing it I'll be getting the email from the client from the forget password component which I just created and I'll be collecting connecting with the database and I'll be checking if the user with this email id exists or not if it does not exist i can actually write not here then i can change this message okay so email does not exist all right so here we are checking if the email exists in the mongodb or not okay so i'm going to remove everything from here this is going to be a long api route because we need to check a lot of things inside it so we have checked email existence after that i'm gonna be using a package called crypto so this is going to be coming from crypto all right you don't need to install it it's already available in the backend api routes all right so using this crypto i will be creating a reset token and the reset password token and the expiry date as well which i just showed you in the mogo db okay so for creating it i'm going to be creating a variable so reset token equals to i will be using the crypto dot random bytes function and i can give it a value 20 you can go through the description from here okay so this is the length of the total alphabets that will be added in this token okay and after that i will be converting it to the hexadecimal so two string hex all right so this has been generated now one thing is that we can store this reset token in the url that we will be passing it to the email id and we can use store this reset token in the user model in the database as well but for security purpose we don't need to store the same reset token in both the url and in the mongodb database it can cause problems believe me okay so for this reason to avoid this problem i'm going to be creating another token so i can name it password reset token equals to and i will be using the crypto package dot create hash And I will be giving it a value SHA256. You cannot change its value. Make sure you add the same.

And I will be updating it by passing the reset token. We need to pass it because. Once we will be validating the token which is in the URL and which is stored in the database. This is where we will be using the built-in function of the crypto to validate the equality between two things. Okay, so after this I will be using the digest and then the hex all right so this variable is something which i will be storing in the user model in the database and this is something which i will be sending an email id by constructing a url which user needs to click on to reset their password after this i will be creating the password reset expire value okay so i will be writing the password reset x expires equals to I can use the date function plus 3600 it is in milliseconds so this value is equal to one hour okay means that our password token will be expired after one hour we will need to regenerate it in order to change our password okay so now what i'm gonna do is i have actually fetched the particular user if user exists this is where the user will be existing in this particular variable so i can use the existing user dot reset token equals to password reset token.

Okay and then I will be using the existing user reset token. expiry equals to password reset expires and after that i will be constructing the url which i will be passing to the email id so i can actually use the local host in real application we need to fetch these base urls from the env files because we can have the staging server production server so in the real application we will not be using the local host over here this is just for example all right so i can actually actually create this reset password route which i have not created yet which is the front end component route okay and after this i will be using the dollar sign and the reset token all right there is one thing that i need to do you guys who have worked with the mongoose models that it will not work because i have not updated my user model that i created using the mongoose okay so this is where you can see that it only able to contain the email password and the timestamps which auto generates i need to add couple of more things which i have added over here so one is the reset token which i need to add here so let's add an object so it will be of type string and it will not always be required okay because while creating new user i don't want it to create any problem so it is throwing any error actually we need to add it like this all right so after this what we have here we have the reset token expiry so let's add that colon this one it is going to be type of date and required equals to false as well all right now when we will be updating these couple of properties for this user model it will not cause any problem url which we have constructed let me log this url So reset URL. All right. So I'm not sending any email yet. I just want to print the URL in my terminal and see if the user model gets updated in the database or not.

So let's try and test our functionality, which we have implemented so far. So let's go to the browser. Let's refresh. Let's go to the page and let's go over here. Let's click on the reset password.

First of all, I'm going to be checking if the user exists or not in order to validate if this particular condition okay so currently there is no user so i'm going to be writing the umair dot imagine three to one at gmail.com click on the submit um actually it is currently so there seems an error um all right so i spelled wrong i think so this has to be the false all right it happens now it's happening let's refresh let's try with the email id which does not exist in the database for now so even if i click on the submit it will not work the reason is that we have created this api but we are not using it we have to go to let me close the user model and currently you can see that in the handle submit we are not calling that api the forget password So let's try to implement that. So I'm going to open up the login page and I'm going to copy. In fact, I'm going to open up this register one and I just want to copy the overall structure. So this is the overall structure of the try catch block. So I'm just going to copy this one and I'm going to paste inside the handle submit function of the forget password.

So here we have the API slash register but we we need to change it to forget password and the method is post we are not passing any password over here we are only passing the email id so the email is already exist if it is four so i'm actually changing this particular error so user with this email is not registered all right and if it is 200 we are automatically setting this error message empty and we are navigating to the login page this is where we can show some kind of toast if you want and if there is any kind of error the server is not running or taking some time i'm just showing this error so we can actually test this now let's save this file and it will call this API on localhost slash colon 3000 slash API slash forget password and it should connect to the database and check if the email exists or not so let's refresh first of all and I'm going to change its added email ID let's click on the submit so user with this email ID is not registered so this particular logic is working fine let's try to register this user so I'm going to change the password first of all so that i know currently i cannot see what was the previous password stored here a b c d one two three four click on the register so it will be registered let's go over here just to verify if the user is registered yes it is registered with encrypted password this is what i've already explained in the previous video how the register process works using next auth and store the user data in the mongodb so let's go to the reset here and now I'm going to use the same email id which is registered in the database. I'm going to click on the submit. So once I click on it it will not navigate the reason is that you can see that it is throwing an error because I'm not returning any response from here just like over here. Alright but I'm using the console ninja package which automatically outputs the console.

log data in the vs code but here you can see that it is correctly constructing the url including the reset token in the url which i will be sending to the user's email id so using this particular url they can click on it and navigate to the reset password route where they will be filling out the new password and they can update their password using this token which we will be storing it in the database so to send the email id i need to configure the send grid send grid is an awesome service it is a paid service but i'll be using the free service there is some limitation so i'm going to navigate to the send grid you need to create your account in the sendgrid.com and once you create your account you need to log in it with and navigate to the app.sendgrid.com first of all you need to go to the settings from the left bar and you need to click on the sender authentication when you send an email you need to configure the sender email id and you need to verify it if it is your particular verified email id and i've already configured this particular email id and i have validated that i am the owner of this email id so whoever is going to receive the email id they will be having uh they will they will be having this particular email ID as a sender. And we can also authenticate the complete domain. If you belong to a company, then all the email IDs belong to that company or a domain will be authenticated as a sender.

OK, so after this, I need to create an API key. Click on the API key from the left bar in the settings. And here you can create a new API key by clicking on the full access and clicking on. the create API key and I can actually write the next 14 here and click on create and view okay so this is the key have been generated and it will not be shown again so I have copied it let's click on the done and I'm going to create an ENV variable so from that I will be using this key so I will be creating a new name inside it so let's name it sent grid API key so let's write send grid underscore API key equals to paste all right so let's save it we have actually configured the send grid now we need to use the send grid in our project so for using it we need to install a package I'm going to come to the terminal and I'm going to write npm I at send grid forward slash mail okay so I'll hit enter so it will be installed once it's getting installed let me import it so I will be writing s gmail from at send grid mail all right so it is installed now using this package i will be configuring the title the body and the content inside the body to send an email to a particular user and you know that we have already got this particular user and it contains the email id to which we will be sending our email all right so here i'm going to construct a variable which is the body you So I can actually write the reset password by clicking on following URL.

We can obviously make this UI look better, but this is what we'll be sending to the user email ID. OK, so I will be appending it with the reset URL, which I have constructed above. OK, so after this, I need to construct a complete object.

Let's say a message. So what is that? So this is going to be to email which is being passed from the client side over here.

And after that, what is the from ID? And this is what I have already registered in the send grid. If you have registered any domain of your company, any email ID belongs to this company can send the email.

So let's add the reset password as the subject and the text is equals to the body the variable which i have constructed so this is the complete metadata of the email which needs to send now i will be using the s g mail and i will be setting the api key first of all so api key process dot env dot send grid which i have created over here let me copy it so send grid api key over here or empty all right this is just for uh validation uh so and not ng it is the s gmail so i have set the api key over here now i will be using the s gmail dot send which is the message it returns us the promise so i will be using the then and this is going to return us you a new response so next response i can uh show any message so reset password email is sent and we can return some status to the client all right so and if there is an error we can also handle this so i can write the catch block over here So I can write the async error. All right. So inside this cache block, first of all, I want to delete the reset token and reset token expiry. To undefined, it will delete everything.

These couple of properties from the model in the MongoDB. So undefined an existing user reset token expiry equals to the undefined. okay and after this i can actually uh use the await existing user dot save all right and if there is an error i can simply return an error message and this is how it's going to fail sending email try again with the status 400 this is what i'll be receiving in the front-end application over here all right uh maybe over here or here uh if it is 400 status all right and outside this stmail so we have handled sending email and if it throws an error after this we also want to add the try catch block and I want to save the user existing users save and here I want to return some kind of message so it will be 200 and I want to email is sent for resetting Password so we can write anything over here. So there seems an error So I need to add the catch block with the error and inside the catch block I can return new next Response error and then status is going to be 500 all right. So this is how our complete code of this API is looking like it is actually showing some kind of so I can write any over here so it does not throw any error all right so now I need to verify if the user email is sent successfully to this email ID which is trying to reset their password so let's see if it works let's save it and I'm going to run the project and see if it starts working so let's go to the browser and i'm gonna open up this let's refresh this page and i will be writing it where jamil321 at gmail.com so i'll be clicking on submit all right it should successfully navigate to the login page first of all because Yes, it has successfully navigated to the login page.

The reason is that it came back to the front end and this is where it is navigating to the login page because the status was returned 200. So from the screenshot which you are looking at currently is my email client and this is what the email is looking like. Currently, if I open up this URL in my browser, it will not navigate because I have not created. reset password route currently in my next.js application this is the next step to create the front-end reset password route so let's work on it before that i want to show you this data of the user in the mongodp that these two properties have been added over here all right because the email is sent successfully and we are adding these two things in the user's model all right So now let's go ahead and create the reset password component.

So I'm just going to remove everything for saving our time. I'm just going to copy everything from the forget password component. And I'm going to create a new component here. So I'm going to write the reset password, which is a component.

And inside it, I'm going to create a new file. So page.tsx. All right.

So let's. paste everything from the forget password component and i'm going to change the name did i change the name of that forget password let me go i did not change so make sure you change it as well so we can let me change it to forget password here as well it will not affect because i'm not using it anywhere outside this component It's just a route file. All right.

So let's close it. And also here, I'm going to change its name. So reset password.

Let's copy this. Let's paste it over here. All right. So let's see what we have here. First of all, one thing I have missed.

I want to create another folder inside it because this is a dynamic route. The email which I have received, it will be added in the dynamic route. So I will be adding token within this square brackets. All right. And I'm going to move this page inside this token folder.

All right. So now our URL will become localhost colon 3000 slash reset password slash the dynamic value will be coming in this token. So this is how we can actually receive it from the params.

So params. And after that. uh we can have a different type since we are doing typescript so for now i'm just adding the any after that so let's receive the params dot token so i can actually log that out to verify if the token is actually getting received or not but first of all let's verify what we need over here we need this thing we need this uh and also we need another state variable and I'm going to give it a name verified set verified so if we are fetching the token from the URL and the token is stored in the user model in the MongoDB we also want to verify if the token is correct that is stored in the database and the token is not expired as well okay so this is how I will be using this state variable for this reason and Now I will be using another state variable which is going to be a user and I will let you know why we need it. So I will be using use state so initially it will be null all right and we would need it this one so let's leave it like this and this is going to have a use effect as well so i will leave it as is but above that we can actually verify so whenever we will be navigating to this reset password component i want to verify the token validation and i will be creating another api for this purpose So we can use effect and it will be running without any dependencies. So I can add the empty array as well, but I can also pass the params.token as well, which is coming from that URL.

All right. So inside this use effect, I'll be calling an API that will check if the token is valid and not expired. OK, so here.

This is where we are checking the email ID which we don't need here and I will be using it later on. Okay so let's remove it. I will be getting the password over here and this password is going to be passed to the reset password API which I have to yet create so we can actually pass the password all right uh along with the password we will also be passing the user's email id because without passing the user's email id we will not be able to check that which user's password needs to be updated so for now i will just be commenting this whole code within the handle submit all right So but for now, I want to focus on this particular use effect creating its API and verify the password. But quickly, what I'm going to do is I'm going to change it to the reset password in the UI. And this is going to be a password.

Okay. And this is going to be a password here as well. And after that, we have this button.

okay so this is going to be a reset password all right so i'm just going to remove everything from here um i don't need that so we have this reset password below this uh we have this or i'm going to remove this as well we'll be showing error over here reset password button having the submit and also i want to have this disabled equals to error dot length greater than zero all right the reason i'm disabling this button if there is an error so when can be there an error so when the token is expired or token is invalid then i will be adding the values inside this error which will be showing over here And then I will be disabling this button. So user should not be entering the password in this input field and clicking on this particular button. All right. So first of all, what I'm going to do is I'm going to create an API for verifying the password.

So let's create an API inside the API folder. I'm going to create a new folder. So let's write the verify token and inside it.

Let's create a file. so i'll be name it route.ts okay so inside this route.ts i can actually copy the overall structure this one let's copy it and paste it over here so let's close it like this so we can avoid different errors we need the crypto we don't need to send an email here we need next response we need connect we need user okay so here i will be passing the token from the client side from this reset password this use effect okay this is the client and this is the server side code this is what you need to understand because we are inside the api folder all right so once the db is connected i want to hash token equals to crypto dot create hash and i will be passing the same value which i use to create this hash token and after this i can update with this token and then i can write the digest hex all right uh you remember that the url token is different from the token which is stored in the user model in the database and that is the reason i'm converting it into the hash token and using this hash token i can check if the user exists with this token or not okay so after this i can write the user equals to await user dot find one reset token let's verify reset token equals to the hash token and then reset token expiry make sure you enter the same value over here and this is called the aggregation in mongoose so i can write the dollar sign greater than Date so I'm checking here if the token is not expired using this validation alright, and if User exists if it does not exist then I can simply return some kind of response Let's copy some kind of response from this file and I can paste it over here So I can enter a message invalid token or has expired okay so after this i can also return the success response that i will be passing the stringify not inside this so json dot stringify user and then status equals to 200 so i am passing the user and this you this is how we can return the data Using this next response if we don't want to return any string. Alright, so I think we are pretty much done with it So let's save it now Let's use this API slash API slash verify token in over page dot TSX To check if the token is valid or not so inside it what I'm gonna do is Let's come here.

And first of all, let's create a function verify token equals to async this arrow function and i'll be calling this function from within so verify token like this all right so now uh i'm going to copy the whole structure from here i don't want to write this try catch block again and again so let's copy it like this so let's uncomment let's save it so it intent properly and this is not the reset password here this is going to be the verify token this is the api and this is going to be the post request colon and we will be passing the token inside it so it will be params.token and if it is 400 then we will be setting an error and i will be setting the set verified equals to true as well you okay so this is this is because um for the validation so let's add the errors so token or has expired okay so this verify variable is actually checking the process is completed the process of checking the validation of the token okay so this is going to be an empty and this is going to be the set verified true okay so i'm checking uh the complete process over here um and after this uh we are checking it uh let's try this thing we can have user data equals to await response.json okay so this is the response which is coming from that api from here okay so i need the user data so we can actually change the password for a only particular that user which requested to change their password okay so and then i can write the set user data equals to the user data let's see if we have here so this is the set user over here not the set user data okay So I think we are done with verifying this token and we need to verify it if it's working fine or not okay so i think i generated this url which is stored in my email id and the one hour is not passed so that token is still valid so let me copy up that particular url and see so let's hit that url so i'll hit enter so here you can see that it is not showing any kind of error maybe so If I change the token from the URL, let's see what happens. Hit enter. And now you can see that it quickly run this use effect because we have added this dependency over here.

And it called this API which we have written and it is validating the token if it is valid or not. So earlier when the token was correct and the token was not expired, it did not show this error. And...

Now it is showing the error and this button is disabled now currently I'm not able to click you can see cursor is changing the hover effect as well which I which you can obviously which you can update this based upon this condition. It's up to you like but it's hovering in case if it is disabled or enabled in any case but I'm not able to click on it because the token is expired. So let me add the correct token. Now it's not showing any kind of error because the token is validated and I can still change the password after this. Now, what we need to do is we need to create an API for changing the password and we need to create the code inside this handle submit button.

So first of all, what I'm going to do is I'm going to create an API road first of all, to reset the password successfully. and update the user model in the mongodb database so let's create a new folder inside the api folder and i'm going to name it reset password okay don't get confused because i'm using the same names inside the api folder and the same names for the routes so inside it let's create page dot not the page it's an api so route dot ds all right So for now, I'm just copying everything from the verified token code to get the overall structure of the file So here we don't need the crypto one thing we need is the bcrypt package because for registering a User if I show you this is the register user route I used bcrypt to encrypt the password before storing it in the user since we are Handling the new password, we also need to use the same bcrypt package to actually encrypt and hash the password before updating the user model in the database. So I'm just copying the bcrypt.js.

I need to install it yet. So I'm going to write npm i. So bcrypt.js.

So I'll hit enter. So it will be installed. Now inside it, I will be receiving the password and the email of the user.

to which i want to update the password so this is the new password which i'll be receiving from the client and this is the email of the user of which i will be updating the password and i don't need this thing i will be using and checking if the user exists so const existing user equals to await user dot find one I can find it by email only as well. Okay. So the reason I'm fetching the user because I want to update the password field and save it after that.

Okay. So now I'm actually using the hashed. In fact, let's open up this register and I'm just going to copy this one.

All right. So let's go over here. Let's paste it.

So this is the hashed password. with the new password all right and after that i'm using the existing user dot password equals to hash password and once it is added with the new password i want to make the reset token reset a token expiry to the undefined okay so existing user dot reset token you equals to undefined an existing user dot reset token expiry Equals to undefined. Okay, and after this we can Save the new user and we can actually return the response So I'm just going to remove everything we can use the try catch block as well So I will be writing the await existing User dot save which is saved and then I can return the response So let's return the response I will be user is what I can do user users password is updated any message and then I can have the catch block as well like this let's copy cut it paste it and I can simply print the error over here With the 400 or 500 Let's add the type for it Alright, so I think we are done with it So let me recap.

So I'm receiving the password and email ID. I'm using this password to hash it again and i'm using this email id to get the user to which i will be updating the password for and then i once the password is updated i will be uh adding the undefined to the reset token and the reset token expiry to this all right so now uh i will be saving it now i need to use this api reset password in my page dot dsx let me run the project as well so npm run dev Okay, and I commented this code. Let me uncomment this.

And here I'm already calling the reset password and I need to pass the user email as well. So since once it was validated, you can see that here I'm getting the response from that user. And here I'm storing it in this particular state variable. So I can get this one.

user from here okay so let's come over here and passing this email from the user dot email okay this is the state variable all right and then what I can do is I'm checking if it is 400 we can check like any error message something went wrong obviously you can optimize these errors and also we are getting errors from the response as well we can use those error messages as well and after that we are navigating it to the login page and error try again or something like this all right so one thing i want to add over here that i also checked this set verified okay So I want to show the loading bar since I'm showing the loading bar based upon the authentication over here. If I'm checking if the user is authenticated or not, but I also want to add this loading bar until and unless I'm not verified. The process of verification of the token is not completed.

Until then, I want to show this loading bar. all right so let me save this file i hope that it will work fine so um let's see so you can see loading bar is showing up um it's actually validating let's see mongo could be connection successful and now this token is valid i think because we set the expiry date to one hour you remember that i updated the password you to abcd1234 now here i need to update the password but also let's refresh this we can verify it from here as well you remember that the last two digits of this password is gvi if we are able to successfully update the password it should be updated here as well and obviously these two properties will be removed from here and gvi should be removed from the token this is just for me to remember otherwise the whole code will be updated okay so let's go over here this one and i will be adding the new password a b c d one two three four five six seven eight nine zero so i have completed all the digits so Let's click on the reset password and if it goes to the login page and yes it has gone Uh, we can see that it has been added over here Let's go over here and see if this has been updated or not. Let's refresh And all right guys, so our password is updated Uh, and let me zoom out and now you can see that this is not gvi means that the password is updated over here as well and those tokens have been removed here as well so here let's go and try to log in with the old password so let's click on the sign in yes we are not able to log in let's try to add a new password so a b c d one two three four five six seven eight nine zero let's click on the sign in and yes we are able to successfully log in so over forget password reset password functionality is completed and we are navigated to the dashboard which is the protected route one thing i want to verify here i want to navigate to the forget password route here so let's see if we are logged in are we able to navigate to the forget password let's hit enter and yes we are not able to navigate to forget password because we are authenticated and similar to that and everything is being handled through this check okay This check is handling everything and also we are using this use effect.

It's checking if we are authenticated then we are navigating to the dashboard route and we should not be able to navigate to the forget password. We should not be able to navigate to the reset password page as well. So let's navigate.

So it will be navigated to the dashboard because we are not successful. We are not logged out. currently so let's click on logout one thing more i want to verify here uh let me copy that url since over a re password have been reset if i try to trigger the same url again okay let's see what happens so let's run and now you can see that invalid token or has expired and our token is correct the reason it is showing that because we have already used this token to change the password and it has been removed from the database as well so in order to change the password again we cannot use the same token we need to regenerate that token so this is how the whole flow is working and our complete authorization authentication process have been completed so i just want to request you guys you can see i'm putting a lot of effort building these videos for you guys so it's just a request to subscribe my channel and like this video and hit the bell icon as well so you get the notification for upcoming videos so if you have learned something new do comment below and share these videos with your friends i hope that you have learned something new and you have got an idea how the authorization authentication process works including storing the data in the database forget password reset password verifying token how to generate token and it is a kind of advanced concepts but i have tried to complete it with easy steps and easy explanation so it will really encourage me again guys to subscribe my channel and like this video and thank you so much for watching see you in the next video