JWT Authentication with React, Node, MongoDB and Express 🔐

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey youtube i'm kishan and in this video we'll learn how to use jwt for authentication using react node and mongodb you will also learn how to use cookies with react and node so let me show you the demo of what we are gonna build so this is the register page and we also have a login page and there is a route here which is protected by jwt so let's register a user now we have several validations here now i will submit the form you can see that there is this validation of email is required this is from the backend now i will give it a email and i will submit the form now you can see that there is another validation of password is required so we'll give it a password now i will hit submit first of all let me show you the mongodb i'll refresh this you can see that there are no users and i will submit this now you will get this beautiful message and we are into the super secret page this is protected by jwt and i will hit the refresh button here you can see that our user is created and the password is also encrypted we have used bcrypt for encrypting the password now i will log out this user and this is the login page and now i will login our user we have logged in now i will go to the login page and you can see that we are being redirected to the super secret page because our jwt key is stored in our cookie so let me show you that you can see that in the application we have this jwt cookie now whenever this page is loaded it will check if there is this jwt cookie if there is not the jwt cookie then it will redirect to the login page so now let me uh change the value of this jwt key i will hit enter and i will refresh the page so you can see that we are being redirected to the login page and also the jwt cookie is deleted now let me log in the user again and you can see that the jwd cookie is created and i will delete this and i will refresh the page so we are not able to access that super secret page because we don't have the cookie so that's it without wasting you further time let's learn how to use jwt for authentication using react node and mongodb so now we'll start setting up of our jwt app so i'll open a new terminal and i will write npx create react app and the name of our app would be public while this is being created let's open a new terminal and we'll write mkdir server this will create a server directory here and will move into the server directory now we'll write npm in it dash dash yes so a package.json would be created with default options okay it has been created you can see that package.json has the name of our application version scripts and all now will install some dependencies we will write npm install express then we need nodemon we need course we need cookie parser cookie parser then we need json web token json web token and we will also need bcrypt yeah that's all while this is being installed let's create a new file index dot js this should be inside the server directory okay it has been installed let's close this and let's import the express const express is equals to require express then we'll write const app is equals to express now we'll write app.listen on port 4000 will create our server this would return a callback function and we'll write console dot log server started on port 4000 that's it now let's start our app before that let's move on to package.json and in the scripts here we'll add our own script we'll write start and the value would be nodemon index.js so what this will do is whenever you will save any of the file inside the server it would automatically restart your application so let's start this by yarn start okay here is our message server started on port 4000 also react application has been installed let's move on to public directory of its right cd public and what dependencies we need inside the react application so first we need a react router dom for routing so we'll write yarn add react router dom then we need xcos for api calling then we will also need react cookie for cookie passing react cookie and at the end we'll also be needing and react 265 library for tools notifications to c5 hit enter this would install the dependencies let's wait for that okay while it is being installed let's remove some code from this public source so we do need this file this one this one this and this let's delete all of those go to recycle bin and inside the index.css we are going to delete all of this code inside the app.js will do the same and will create our own component then inside the index.js we are going to remove this input and at the end we are going to remove this comments and this function call that's it let's start our application by yarn start wait for it to compile okay so our react application has been successfully set up now we have some things remaining in the server so inside the index.js of server we have to do some more things here so our app is started but we also have to require course for calling apis from another url to our server so we need course so this is require course and after app.listen we'll write app.use and we will call course and we'll pass an object here so in the object first will path pass a origin path so this should be your url in our case it is uh localhost 3000 but if you have hosted this app anywhere you have to change this url according to that now we are gonna apply the methods so we are gonna use two methods in the app which is get and post so we'll only mention those otherwise any other request like put a patch that would be blocked so if you want that you have to add here and at the end will pass this credentials as true okay that's done and after this we'll also write app.use express dot json so this would have access to json data in the api request so that's it yeah we have to do one more thing we have to install the mongoose package for mongodb did we install that no we didn't install that let's install that here we'll stop the application by control c and i'll write yarn add mongoose yeah that has been installed now let's start the application first yarn start and after this app.listen first we'll require the mongoose const mongoose is equals to require mongoose and after this app.listen we'll pass mongoose dot connect and we'll pass mongodb columns localhost colon27017 jwt so first let me explain this so we are passing mongoose.connect connect function and inside that we are passing our url this is our local mongodb data database which is this and we are connecting it to the jwt database if you are using a online cluster of any mongodb you have to replace this url now after this will pass some options that is use new use new url parser to true and use unified topology use unified topology as true that's it and after this has been connected it will return in promise so we'll chain it with then and we'll write console.log db connection successful success full and if we have any error connecting our mongodb database we will have the catch here catch error pass an arrow function and we'll write console.log error dot message that's it so let's start our terminal and you can see that dbconnection successful message if your database has been started correctly you will have this message or you will have any error if there are any error so yeah that's it so our server is set up no we have to set up our controllers middle models so i think we'll do that afterwards let's head over to app.js first here for the public and here what we'll do is we'll import the react router and we'll have our routes so for that let's create a new folder named as pages pages and inside that will have login.jsx component register.jsx and secret.jsx this page would be protected by gwt so i'll write rfc to create the component register rfc and secret rfc now inside the app.js i'm gonna import from rrd react router dom and from react router dom we need browser router then we will need routes and at the end we need route save it and inside this we are going to remove this and we'll write first browser router inside the browser router we will have routes save it and inside this will have route will provide the exact and will also provide path so the path would be register and the element would be register page register let's copy this paste it two times and here we'll change this to login this would be secret let's change this to login and this would be justin slash yeah that's it let's open our browser okay so you can see that at the slash we have the secret let's head over to login route login so we have our login and now register so we have the register so yeah this is good now i have written some styles which are in a just github repository i will just open it wait for a minute so i have opened the gist you can find this url in the description of the video it just has the css file we are gonna copy all of this code from here and paste this inside index dot css we don't need this now you can see that these childs are applied here automatically so we don't want to waste any time for the styles okay let's check ah that's it so our base setup is complete now now we'll do the register functionality so now we'll have a register function id first we'll create the register component so inside this register one minute so inside this register we'll remove this and we'll give it a class name of container then after this we'll write h2 and we'll write registered account register account make sure the elements and the class name are correct before we have because we have copied the css so it would be applied automatically then we'll have the form we don't need the action attribute and inside the form we'll have a div inside that we will have a label we would have email html for email and this would have text as email will have an input of type email the name would be email the placeholder would be email as well that's it now we are going to copy this div paste it here and we will change this email to the uh password this would be password as well let's do the same for after that password the type would be password and the name would be password as well okay so that's it now after this we'll have an button the type of button would be submit submit here we'll write submit after the button will write span and inside this pan will write already have an account we'll use the link tag from react router dom link it's not being auto imported we have to input from it from here input from react router dom we need the link component link this one and we'll use it here link inside this will have our login and this would have and do prop 2 slash login and we will also need the toast container for toast so we'll write used contain let's input this first react boostify will need toast container and will also need toast that's it so after this form will write boost container that's it let's head over to register slash register we have a form here and when we click here we'll have the login page so yes the markup is done now let's create this state values to store this email and password in the state so we'll use u state here use state we'll write const values and set values is equals to you state and will pass an object with email as blank string and password as blank string that's it and inside both of this input at the end we'll write on change on change this would be an arrow function will have the event here we will write e dot target dot name and the value would be p dot target dot value so we have to cut this and we'll write set values this would be an object will spread the values and will overwrite the current input value so that's it so yeah that's it we have maintained our state for this now after this we'll prevent the form submission so for that we will have const handle submit is equals to an arrow function we'll write e here for the event and we'll write e dot event default so i'm not saving this file so whenever we'll submit the form you can see that there is this uh question mark email and password so because of the form tag the form is automatically being submitted we don't want to do that we'll do this by our own so we'll remove this and we'll have this function and we'll call this here form on submit will have the event and we will call handle submit and pass the event there so let's test this submit and yeah nothing is being done now it's correct okay let's do one thing we are going to copy this component and inside the login.jsx we'll paste the code here and we'll just rename this register to login and we'll have this as login account and this would be register this would be registered as well let's head over to register and you can see that our both the components are ready so we'll do the register functionality first so now after this we are gonna call an api and pass our data to that so we will require xcos import xcos from axios and now after this we'll wrap this into try and catch whenever you are calling any api you should grab the code inside try catch block so we'll write const data this would be destructured from the axios response await excuse dot post okay we have to write equals here and this function should be a sink because we are using async await will pass http column slash localhost column 4000 register and this would be values will destructure the values here so email and password would be sent to the database that's it and in the catch block we'll just console dot log console.log the error that's it now when we hit this submit button we are not having any error why is that okay we made a mistake this is inside the login we have to do this inside the register so i'm gonna copy this and paste it inside the register here register and yeah we have our error x us is not defined let's copy this paste it here submit and we have our error the route is not found because we have not set up our api in the node.js so let's do that so in the backend let's create a folder routes this should be capital after the routes we'll have another folder as middlewares will have the controllers folder so we are following mvc architecture here controllers then after the controllers at the end we will need models we have models so now let's move into the controllers folder and i will create a new file auth controllers or controllers dot js and inside here i'll write module dot exports dot login first we need the register module.exports.register this is register is equals to async request response and next that's it let's copy this paste it have a space and instead of register this would be login let's have a space at above also save it and now let's move on to the routes and we'll write auth routes here auth routes dot gs and inside the auth routes we'll create our routes first so first we need router so we'll write const router is equals to require express dot we'll call the router function here only but this should be capital router that's it after this router will write router dot post and the first would be register we'll use the register from the controller's auth controls it is auto imported above you can see that now i'll copy this paste it and after this we'll have the login let's have login here also it should be auto imported not like this write login yeah this one you need this login and at the end what we are going to do is we will write module dot exports is equals to router now while we are here let's have a router dot host for slash so this is for the secret page we'll have a check user middle middleware here that would be from the auth middlewalls we'll do that afterwards now let's move on to the index.js and we are going to import this all routes up up above here we'll write const auth routes auth routes is equals to require in the routes directory we have our routes let's have it and at the end we'll write app.use whenever we will have the slash api so for all the things we are moving to auth routes that's it now while we are here let's have the cookie parser also so we'll have access to request.cookies or response.cookies so we'll write const cookie parser cookie parser is equal to require cookie parser and this cookie parser will use this above here app.use and we'll pass cookie parser here where did it go yeah this one that's it now what we are going to do is we will create our uh user model so we'll write user model dot js and inside the user model will create our mongoose model so first we'll need mongoose const mongoose is equals to require mongoose now we'll have our user schema const user schema schema is equals to new schema mongoose dot schema and will pass in an object this would have the properties that are going to this model so we'll have an email now we'll validate this this the type of this email should be string then we'll have a required property to true will not pass true but instead will pass an array and the first value of the array would be true so this should be required and if it is not passed we will pass and custom error message so this should be email is required so we don't know how to handle this messages by our own mongoose will throw automatically so that is a much cleaner way then we'll pass unique to true so every email should be unique then we'll have an password this should be an object the type would be string string then will pass required as an array and first would be first value would be true and the second value would be password is required password is required that's it now after this is done at the end we'll write module dot exports is equals to mongoose dot model will have users make sure that u is in capital if it is not you have to make the changes accordingly so we'll write users and then we'll pass user schema that said so our mongoose model is ready now let's head over to auth controllers and inside this login controller we'll have our details so inside the login what we will do is first we'll have our code inside try and catch make sure to do this every time now we need our email and password from request.body will be sent we have sended that let me show you we have sended these values these values contain our email and password so it is an object as you can see and this can be accessible into request.body so let's head over to auth controllers and we'll restructure that from requested body so we'll write email email and password is equal to request dot body and after this is done now what should we do yeah we'll first write const user is equals to await user dot create that's it and we'll also pass email and password that's it now this would create our user whenever you console this user you will have a new user here if there would be a any validation error like you haven't passed any email so mongoose will pass and validation error of email is required and password is required and if any email is used because of unique property here that we set where was it yeah inside the user model we have passed this unique true if there is a valuation of this property then we will get an error code of i think 11 000 yeah that should be 11 000 so we'll handle that using our custom error function so let's head over to auth controllers so after this is created what should we do let's create our jwt token so for that we'll create a new function here const create token and this should be an arrow function that's it arrow function and inside will have our id that is the user id which is written by mongodb so we'll have create token and will return will also import gwt here const jwt is equals to json web token require require json web token so after the after this written we'll write jwt dot sign this one this will assign a new uh jwd token so we'll pass the id inside the token and we'll pass our secret key this this will use to decrypt this jwt token after this is created and stored in the front end i will show you the jwt token and what's inside that give me a minute so i'll write my secret key here this should be anything you can set anything private but make sure you remember that if you forgot this then the jwt token would be not accessible so i'll write question sheet super secret key and after this i'll i'll give an options object this has various options but i'll just use xpars in so we are gonna expire this in first let's create a max h is equals to 3 into 24 into 60 into 60 so this is for three days after three days our jwt token would be expired in the cookie so we'll pass that here max age now we'll use that here after user is created what we will do is we'll have our token cons token is equals to create token and will pass user dot underscore id that has been written from mongodb make sure that is underscore id then will pass this token inside the cookie so we will write response dot cookie this should be c double o k i e response dot cookie will pass jwt will also pass the token and will pass an options object so we'll write with credentials with credentials as true after with credentials we'll write http only as false because we are gonna access this from an another domain or another port then we'll write max h as max age in 2000 that's it okay that's it now we'll write response dot status as 201 dot json will pass an user here so the user would be user id user underscore id and will pass created as true this should be user dot id that's it now inside the catch block now inside the catch block here we'll write console.log error and we will create our custom error handler at above but first let's use this and see if it is working at the front end so [Music] i think some code is pending inside register yeah it is pending so inside register what should we do next is if we receive the data here if data and if the data contains any errors errors will have this if condition or will have else condition appropriately let's console the data we'll complete this afterwards let's console the data first let's head over here refresh this now we'll have an email and give it a password first of all let's give it a password one one one one one did we call our api yes the api is being called but no responses there let's check in the console do we have any error no we don't have any error why is that did we nest anything in index.js cookie parser course everything is working perfect let's do one thing inside the auth controller okay we had to write this inside the register not the login that was my mistake sorry inside register let's give it a try again we'll submit this and yeah we have our response of created true and we also have console did we have any error here no okay so our user is created and let's see inside the cookies no we didn't have any cookies here i think inside the register.js6 we have to pass one more thing here after the values with credentials as true now let's head over to mongodb refresh this as you can see that now our password is also not encrypted we have to encrypt our password first so we'll also do that first of all let's delete this user give it a submit and we should have received any error inside the console as you can see that we have console error here we should handle this so we'll do that also let's pass a user question sheet 123 subnet api is called did we receive our cookie response headers i think we didn't receive our cookie here yeah we received our cookie and you can see that it is here gwd okay that's good now i'll show you what's inside the jwt key give me a minute so we are in the jwt dot io website so this is the jwt token so this is not our token we'll just grab our token from here inspect application cookies and this token value copy this and will paste it inside here now as you can see that this part here is the header so it mentions that what type of algorithm is used it is here then this thing this thing is our data so what is stored inside this so we have stored our id this id we will compare this with the mongodb so let's refresh this and you can see this is 622 ending with b3 and this is 62 ending with d3 so that is encrypted inside our jwt 2 con and this is our signature so we'll also we can also paste our uh secret here so we'll copy that from the auth controllers up controllers kitchen shade super secret key copy this and we'll paste this and this is perfect so this is our jwt token so if you have any uh if you have any issues with that you can always put your questions in the comment section now i'll close this now we have to encrypt our password before saving it to the database so i'm talking about this the password cannot be stored as one two three because if your database is uh loosed if it is hacked then this can be accessible and all the user data is available freely so we'll just uh have some validation for that so inside the auth model auth model no the user model so inside the user model what we will do is we will have a user schema dot pre function so before saving this to database this is an type of hook from uh mongodb so before saving this we'll have our function will also have the next year we have to call next it will be stuck here so we'll write we'll use bcrypt for that we'll import decrypt here cons decrypt is equals to require be crypt and inside this we'll use this const salt so we will generate a salt first await dot gen salt okay we have to write await we be crypt dot chen salt and then we'll have access to this here because we haven't used an arrow function we have used the normal functions so we have access to this so we'll write this.password is equals to await decrypt dot hash and we'll write this dot password and we'll pass the salt here so before saving it to the database this function would be run so let's test this i'm going to delete this user again and i'm going to submit this and refresh this as you can see that our password is hashed now and it is secure so that is done now will handle some validations so for that inside the auth controllers will create a function as handle errors uh what should we do there inside the auth controllers yeah let's have a function after this of const handle errors errors is equals to error and will first have an errors object errors this object would contain email and password so we'll manipulate the strings accordingly then what should we do yeah first we'll write if error dot code triple equals to 11 000 then we'll have errors dot email is equals to email is already registered this is registered and will return the errors from here we no longer want to go further so let me show you this error code so i'll use this email again i'll hit submit now open the console and at the end i think there would be herrera yeah server error error 11 000 duplicate key error collection so this is what i'm talking about so you can see that the error code is 11 000 and we have compared it with error dot code if we get this code then we will written an error of email is already registered then what we will do is we'll use another f and we'll write error dot message dot error dot message dot includes user's validation failed so is it passed here no i think your validation field is not passed so what we'll do is i'll remove this and hit submit and we'll have an user validation field yeah you can see that user's validation field error so if this message includes this then we are gonna go further we'll have object dot values and we'll get the error dot errors so we are getting this errors and for each error we'll have the loop we'll destructure the properties pro per ts i'm talking about this properties and will have errors of properties dot path so this would be either username or it should be either password so that would be stored inside this so this is the key and will have properties dot message as the error that's it and at the end we'll return the errors return errors now let's handle those from here so after this console.log errors what we'll do is we'll have const errors errors is equal to require not require we'll write handle errors and we'll pass the error object here so after this we'll have errors as equals to handle errors then we'll write response.json and we'll pass the errors and will pass created as false now all that is left is to handle this from front end let's do that head over to register.jsx here and now we'll have our if else code for the toast notifications so we already have the toast and we'll create another function that is const generate error error is equals to async no this shouldn't be async we just will have the error here error and will pass this to dosed dot error and to start error and the message would be i think error itself and will just pass and position prop position and the position would be bottom right bottom right that's it and we don't need this now inside here we don't want to console the data if the data has errors then we'll destructure the email and password from the or data dot errors data dot errors and if there is an email if email is not an empty string then we will generate the error we will call the generate error and will pass the error no not this will pass email yeah and we have an else block here else if and this has password generate error password and yeah that's it that's let's leave this else block empty now let's submit we have this error email is required but it is not in correct our form i think we missed something form form is here i think this should be outside of container so we'll have this and at the end we'll have toast container let's have it okay i think i know the error why it is coming we don't need this fragments we haven't imported the css file of the toast messages we have to do that so let's do that let's head over to app.js and inside the app.js at the end we'll import import react to stify slash test slash react dot css let's hit submit now okay the error is here email is required let's give it a email password is required let's give it a password and we'll have email is already registered so it is working perfectly now we'll use any another email which is admin and hit submit and the user would have been created as you can see here admin gmail.com now whenever a user is created we will redirect this page to the slash route so let's do that so inside the register we are gonna import the use navigate hook use navigate from react router down and we'll write const navigate is equals to use navigate and in the else block here we'll have the navigate and we'll navigate to the slash route that's it okay never demo one two three submit and we are into the super secret page okay so let's have some code to the super secret page so our login functionality is completed let's head over to the super secret page secret.jsx and inside the secret.jsx we'll just have remove this and we'll write class name is equals to private and we'll give it a h1 or super secret page after this h1 will have a button and this would be lock out that's it will not design this okay while we are here let's uh have the log out functionality also on click on click is equals to log out and what we'll do is const log out is equals to arrow function and first we need the this thing use navigate we'll remove the link grab the hook and we'll call this and we'll have navigate to slash register that's it log out register page login that's it and we are also getting the jwt here so whenever we log out we'll delete this cookie so we'll do that afterwards now let's do the register function uh let's do the login functionality register functionality is completed so now we'll do the login functionality and we'll head over to login.jsx so most of the code is written here it's pretty much the same as register so what i'm going to do is i'll copy all of this copy and head over to login.jsx and replace this all code with it we also have to import the use navigate hook use navigate and it has already been called and here will change the api call to login instead of register so yeah that's pretty much it it is the same as register now let's head over to the server so i'll go to auth controllers we already have created the author out login let's head over to auth controllers and i'm going to copy this try catch block and paste it inside the login and will just change a single line here that is we'll also change this status code this would be 200 and instead of uh await this user model dot create will write user model dot login and we'll pass email and password everything would be same so we have to create this method login inside the user model so i'll head over to user model and after this i'll have a method here which is user schema dot statistics statics dot login this would be an async function we know we don't need the uh okay we made an error here we haven't called the next function here we have to call it after this we'll have a sync function email and password here email password and will have const user is equal to await this dot find one and we'll pass email so first we'll check if there is a user and if there is a user then what we'll do is we'll check the auth that is await bcrypt dot compare password and user.password so we'll compare it with the hash so it would automatically convert this password which is sent from front end to the hash password which is stored in the database it will compare if it is correct or it is not correct so if it is correct it will return true and will write f r then will return the user and if not will throw an error through error in correct password in correct password and after this will also through an error of incorrect email incorrect email so let me explain this first what we'll do is we'll uh find the user from the given email if there is a user so this would go inside that and if there is not the user will throw an error of incorrect email and now in this scenario we have the user then we'll compare the password with bcrypt if the password is true then we'll receive the true and will return the user object and if it does not then we'll throw the error of incorrect password we need to handle this errors inside our custom error function so let's go to auth controllers so everything would be same in here in the login nothing would be changed but above here will have two new cases of error dot message so we'll write if error dot message triple equals to incorrect email this should be same as the error that is thrown from here let's copy this from here only incorrect email and in the auth controllers will paste it here in correct email then what we'll do is we'll write errors dot email equal to that email is not is not registered that's it and we'll copy this we are going to do the same for error dot password so we'll write error dot incorrect password that password is incorrect that password is incorrect yeah so that's it that's pretty much it i think yeah let's test this so we'll use the cushion shade one two three submit we didn't get any error let's open the console let me refresh this we'll use the uh let's create a new user i forgot the password so i'm going to use donna gmail.com and write one two three log out inside the email i'm gonna use donna gmail.com123 submit okay that email is okay we are into the register page we need to go to login page and we'll use donna gmail.com123 we are not getting any error let's check the network tab we are calling the login and it is getting a response of email password created false what is the issue here i think we need to change the code somewhat login.jsx we aren't having any error so we should be navigating to the uh chat page uh not the chat page super secret page so let's head over to login.jsx let's open the console first are we getting any error yeah we are getting error what error is that model users what does this cast to string field for value email okay we are having an issue here inside auth controllers let me do one thing i'll console dot log email and password let's send that that the server restarted before yeah donna and password we are getting it correct then why is this error here let me check that so i have found the issue so in here we don't have to pass the object we just have to pass email and password as separate values it should work now we'll submit and let's log out again so you can see that on gmail.com will not submit the password password is required okay this is register donna submit that password is incorrect will not send the email this time that email is not registered we'll use uh another email here we'll again get that email is not registered so we'll use the donna again donna gmail.com and we'll use 123s password submit and we are inside the super secret page so our login functionality is also complete now what we'll do is we have the jwt toucan inside the cookie here so what we'll do is whenever we go to this page we'll check if this jwt token is not manipulated or it is not expired or it is correct so we'll check this we'll send this to server we'll check that there and we'll have that response accordingly and if it is not correct we'll delete this cookie and we will redirect it to the login page so we'll protect this route so let's do that so let's go to the auth middleware this is not created we'll create it auth middlewares dot js and inside here we will require the jwt and the user model so we'll write cons user is equals to require and we'll write dot dot models user model that's it we also need the jwt to check if the gwt is correct will require this json web token now we'll write module dot exports dot check user is equals to request this should be a function [Music] this should be request response and next request response and next and now we will get the token from the request.cookies.jwt will be sending the cookies from the front end so we'll have it request our jwt dot cookies now we'll check if there is a token gwd dot verify and if there is not a token we'll send response dot json of status as false and we'll call the next function now inside the if first we'll do jwd dot verify we'll pass the token and we'll pass our super secret key which is inside the auth controllers so they should be stored in an environment variable when you deploy it to the server or else anyone would see your code and get this key so super secret key and now we'll pass an async function sync error and the decoded token decoded token now if there is an error we'll just copy this and have the status as false and call next here [Music] do we have an error here because it is not auto saving okay what error do we have here we have to write arrow function here that's it now if we do not have any error we have the else block and now we'll get the user from await user dot find by id remember i showed you that we have the id inside the jwd token so we'll have await user find by id and we'll write decoded token dot id now if there is a user will send response.json status of true and the user would be user dot email will grab the email from the user and if there is not a user we will pass this again response.json status false we don't need this brackets we'll just write this here at the end don't forget to call the next function here that's it so what this condition will do is if there is not the user if the user is deleted from the database then we want to send the status to false we don't want him to access our private information so that is for that so back it back in code is done now inside the user routes we'll just call this function of check user check user that's it now let's head over to the secret.jsx at the front end and we will do our magic here so we'll grab the use effect hook first use effect after use effect will also import use cookies from cookie parser key react queen not a cookie parser react to key and we'll have use cookies this would be like this use cookies and will also import x use from xcos and let's go to the register.jsx and we're going to copy this to container go to secret paste it here at the end we'll have the toast container here used container now we'll have our use effect hook so first let's call the use cookies function so we'll have const cookies set cookie set cookie and remove cookie is equal to use cookies and will pass an empty error here now we'll have our use effect use effect we'll have the dependency errors as cookies and we'll also use the navigate so we'll pass in the navigate here navigate and inside this we will have the function const verify user is equals to async arrow function and we'll call this verify user here at the bottom now inside the verify user what we will do is we'll first check if there is no cookies and will have the jwt access here so there is no cookie here so we'll navigate to login and if there is a cookie we'll call the api so let's grab the api call from this i think this is it will paste it and instead of register we'll just have this empty will pass empty object we don't want to send any data and we'll just have with credentials as true for sending the cookie with credentials as true and now what we will do is if there is no data dot status so not no but if there is the false there then we'll have remove cookie jwt and what should we do we should navigate to the login navigate login and in the else we'll give it a toast toast of hi data dot user and this should be theme of dark if you don't want a dark theme you can skip this that's it we'll also pass the remove cookie here remove cookie and add here before navigating we'll use the uh remove cookie jwd whenever we log out so that's it let's test this now hi donna gmail.com okay we have our toast but it's not correct why is that i think we should do this as fragment this time yeah it is working perfectly now let's reload this page because we have the jwt we have the access here let me do one thing i'll delete the jwt now and refresh the page so we are going to the login page now i'll login as donna again 123 submit now we have the jwt now what i will do is i'll just change the jwt and again refresh the page so as the jwt was not correct so we have the token removed and redirected to the login page so we have implemented the private routes also so that's pretty much it it is completed thank you for watching this video and if you like this video please hit the like button and subscribe to the channel and if you have any issues you can always ask them in the comment sections see you next time [Applause] [Music] you
Info
Channel: Kishan Sheth
Views: 32,323
Rating: undefined out of 5
Keywords: jwt, json web token, jwt react, jwt node, jwt auth, jwt authentication, jwt authorization, jwt login, jwt course, jwt tutorial, learn jwt, jwt refresh token, jwt axios, axios refresh token, react.js, react, react auth, react cookie, react session, react jwt tutorial, node cookie, node session, node jwt tutorial, react security, jwt security, advanced react, react node jwt authentication, react node project, mern stack project, mern stack project with redux, kishansheth
Id: duyv0se4eNs
Channel Id: undefined
Length: 79min 9sec (4749 seconds)
Published: Thu Mar 10 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.