After hours of googling and looking at other guides this is by far the best one. Straight to the point and covers exactly what you need to know about how to use JWT. Thank you.
You are the best teacher I ever seen In my school and UA-cam. So easy, so clear. This is the best tutorial I ever seen in my life. thanks my friend. You really saved my life from struggling with jwt for months. Really THank you man.
Thanks Man, I am from Venezuela, I don't understand much English, but I can tell you that your video is the best, coz there are not videos in Spanish that explained as I can refresh the access tokken.
UPDATE: at 55:20 the correct import syntax would be "import { jwtDecode } from "jwt-decode";". Then also update the initialization of the decodedToken later on by replacing "const decodedToken = jwt_decode(user.accessToken);" with "const decodedToken = jwtDecode(user.accessToken);"
Hi Lama, Thanks for this great Tutorial, I want to specially request if you'd explain how to store the refreshToken in real Mongodb Database and not locally as an Array. I also would love to see what the refreshToken model looks like. would you create a separate schema for the refreshToken or just add it to the existing user model as type "Array" Please anyone can help me in this area, it's really challenging me.
I think it's most secure to create the 'refreshToken' array as part of the User schema. This is what I've done. Then, instead of checking the local array as in this example, we would call an async method to find the user in our DB by Id (which we get after verifying token payload and returning the payload in the callback of 'jwt.verify()'), then check this User.refreshTokens array to see if it includes the refresh token and either add or remove depending on your action.
@@jimenakatu1178 I decided to try completing a full CRM /ERP project and along the Line I met more complex logics and situations. That exposed me to wider knowledge, turning back to check on this one, i found out it was just a walk over. I did it myself.
Why is there a different endpoint to exchange the refresh token for a new access token? This seems like it would make building the UI very difficult as you need to try to hit the endpoint, see if the error is unauthorized, if it is, get a new access token and try again. I think this should be done automatically on every request. If the access token is expired, given them a new access token and continue processing the request.
Hi I have a question. It seems like in this tutorial, you are always logged out after you refresh. In your React Social Media tutorial, you stored your user object in localStorage to let the user remain logged-in after page refresh. My question is, since you need accessToken to do stuff like delete posts etc, wouldn't you need to store accessToken in localStorage also? If you don't store accessToken in localStorage (only store in useState or useContext), after the user refresh the page he/she cannot delete post anymore since the accessToken state/context will be null. But if you store it in localStorage, doesn't this defeat the purpose of jwt, because hackers can see it from localStorage. So how do I use JWT, and at the same time, pass down this accessToken if my user refreshes the page?
@@developerbox3079 This is what I saw from someone's post from stack overflow: 1.When you do log in, api sends 2 tokens (Access token, Refresh token) in response to the client. 2.The access token will have less expiry time (may be 15min) and Refresh will have long expiry time (may be 7 or 60 days ) 3.The client (Front end) will store refresh token in his local storage and access token in cookies. 4.The client will use an access token for calling APIs. But when it expires, pick the refresh token from local storage and call auth server API to get the new token. 5.Your auth server will have an API exposed which will accept refresh token and checks for its validity and return a new access token. 6.Once the refresh token is expired, the User will be logged out.
You can add anything before the access token but it should be separated by space. eg: BeN . The concept is to split the value of the key 'authorization' in 2 parts. So after splitting, 'BeN' & '' will come in an array. You have to take only the real token so that it can be verified with the generated one. That's why lama has used const token = authHeader.split(" ")[1] ;
i faced a problem in auth so i am writing this to help other : if your access token expire after some time then In axios Instance interceptor add "" config.headers["authorization"] = "Bearer " + accessToken; "" because after the token is refresh the axios instance headers will not update automatically . I Hope i was able to explain what i want to say.
It would be wonderful if you could use this tutorial on blog project. I really confessed. I can do only Auth . But i can not implement on blog project.
Perfect!!!!!! i will buy u a coofe! cheers from Perú btw you should make an example like Google auth i mean when you login from other country or device and google send you an alert if you are loggin from there... i hope you can understand thanks!
hocam selamlar, ben daha yeni başladım kodlamaya, videonuzu izledim teşekkür ederim sonra, uyguladım kendi uğraştığım bir siteye, access token ve refresh token elde ediyorum. refresh tokenları backende yönlendirdim orada tutuyorum. örneğin bir post atma işlemi yaparken kullanıcının access tokena erişimi olduğunu kontrol ediyor ekstra olarak, backende bakıp refresh tokenlede eşleşme şartı koydum. video başında dediğiniz gibi kullancı 2 nin sadece ismini bulup işlem yapamıyor. yeterli midir basit bir websitesi için
Hi Lama, Thanks for the tutorial. I'm however stuck when logging out. I'm trying to log out by redirecting back to another page but it keeps failing. Kindly assist
Great tutorial thx! For registering, could you show how to implement admin approval needed before users can log in? This way only approved friends can create an account and sign in.
Just create a separate database of 'temp' users to hold registered users waiting for approval. Allow admins to elevate those 'temp' users to 'active' users, moving them to the 'active' database which is the one you would used to sign users in.
I have a confusion. While logging out since we are only removing the refreshToken and not the accessToken, wouldn't they be technically logged in for the duration of the access token?
help, I'm doing this for my website but when user refreshes the page, the status is gone... wtf? Also, what's the point of a refresh token if you only bind it to a specific axios instance. So, if I go afk for 15 mins, I'll still get logged out, unless i delete a user.
Okay I have a question.anyone help ? When logging out why do I need to verify?I mean the goal is to delete the refresh token from the array.Its all about the refresh token! So why bother sending the access token as well?? We did not send the access token when refrshing,,because that was also about the refrsh token!
How am I supposed to store the refresh token in my mongo database? should every user have their own refresh token so i call it like 'user.refreshToken' or should they be completely separate from users ?
hi, I want that when a person reload page then it still logged in. How to implement this in jwt. I implemented in using local storage but its not good as discussed.
@@Ahmadavocado Its upto you. By the way cookies are also not safe. We're just storing which no one can understand because we only know the key not anybody
you're the MAN... long live Lama Dev
After hours of googling and looking at other guides this is by far the best one. Straight to the point and covers exactly what you need to know about how to use JWT. Thank you.
You are the best teacher I ever seen In my school and UA-cam. So easy, so clear. This is the best tutorial I ever seen in my life. thanks my friend. You really saved my life from struggling with jwt for months. Really THank you man.
A very easy-to-follow tutorial on JWT Authentication in Node/React. Thank you, Lama Dev
{2023-03-22}
Best channel on UA-cam for MERN stack mastery.
YOU TOOK MY REQUEST THANKS, DUDE! ALWAYS WILL GET SUPPORT.
dude wtf, best tutorial of jwt, after checking like 10
Thanks!
Thanks Man, I am from Venezuela, I don't understand much English, but I can tell you that your video is the best, coz there are not videos in Spanish that explained as I can refresh the access tokken.
yo tmb soy de Venezuela bro, lo malo aqui es que si uno refresca la pagina se se cierra la sesion del usuario
thank you for tutorial, JWT is mandatory nowadays.
UPDATE: at 55:20 the correct import syntax would be "import { jwtDecode } from "jwt-decode";". Then also update the initialization of the decodedToken later on by replacing "const decodedToken = jwt_decode(user.accessToken);" with "const decodedToken = jwtDecode(user.accessToken);"
Thank you ! I was waiting for the full reactjs+nodejs make e-commerce website
Really helpful tutorial, I couldn't find a good one for some time and yours is perfect!
Simple clear and concise, thank you very much lamadev !
I was waiting for the jwt tutorial. It's the best as always
The only insightful video on jwt, THANKS!
best tutorial to learn understand and implement JWT. Great work!
It seemed really easy thanks for the tutorial.. Gonna revise again while making netflix clone (streaming platform) ☺️☺️
5 Minutes in I knew it's gonna be a great tutorial. Was right. Thank you!
I love you so much. I want to support you but I lost my job for 4 months.
Your content is the best on internet, thank you very much
Hi Lama, Thanks for this great Tutorial, I want to specially request if you'd explain how to store the refreshToken in real Mongodb Database and not locally as an Array. I also would love to see what the refreshToken model looks like. would you create a separate schema for the refreshToken or just add it to the existing user model as type "Array" Please anyone can help me in this area, it's really challenging me.
I think it's most secure to create the 'refreshToken' array as part of the User schema. This is what I've done. Then, instead of checking the local array as in this example, we would call an async method to find the user in our DB by Id (which we get after verifying token payload and returning the payload in the callback of 'jwt.verify()'), then check this User.refreshTokens array to see if it includes the refresh token and either add or remove depending on your action.
I would also like to see that and the other way that @Karsen LH said
I have been able able to resolve the challenge. Thanks
@@next_codes You did it by yourself or with help of other tutorial?
@@jimenakatu1178 I decided to try completing a full CRM /ERP project and along the Line I met more complex logics and situations. That exposed me to wider knowledge, turning back to check on this one, i found out it was just a walk over. I did it myself.
really awesome tutorial, love the way you explain things
You are the best Lama~!! The content is so informative!! Thank you so much~!
Thank you very much, I really love your videos, thank you for making us better everyday
Love your videos, thanks for the uploads
you are my best teacher.
Thank you Lama, you are the greatest
I love your videos!. Thank you so much, greetings from Colombia
Thanks for your great tutorial
I love your videos. Thank you for this!!
Why is there a different endpoint to exchange the refresh token for a new access token? This seems like it would make building the UI very difficult as you need to try to hit the endpoint, see if the error is unauthorized, if it is, get a new access token and try again. I think this should be done automatically on every request. If the access token is expired, given them a new access token and continue processing the request.
thats what he did right?
@@saravanan925 He created an endpoint to exchange the refresh token for an access token. Is that what you're asking?
Did you watch till the end? There's a function on the frontend that automatically refreshes the access token if it is expired (No UI included)
@@marcusaureliusregulus2833 yeah, why? why not do that on the backend?
@@TomDoesTech I guess it could work either way.
very well explained !! thank you for JWT tutorial
Helpful information, thanks
Another quality content.
Thanks very much, tutorial was very helpful.
Awesome JWT tutorial
You are doiing an amazing Job. Thanks
Nice work. Just want to know why not making use of cookies ?
Abi videoların baya güzel yeni fark ettim kanalı. :) Teşekkürler videolar için.
when do we use JWT over something like Auth0 or Google Firebase Authentication?
Thanks for your great tutorial Şafak. Should we use NextJs framework for fullstack javascript applications? what do you suggest ?
you were ahead of your time when you asked this question XD
You are amazing.
Love you.
Hi I have a question. It seems like in this tutorial, you are always logged out after you refresh. In your React Social Media tutorial, you stored your user object in localStorage to let the user remain logged-in after page refresh. My question is, since you need accessToken to do stuff like delete posts etc, wouldn't you need to store accessToken in localStorage also? If you don't store accessToken in localStorage (only store in useState or useContext), after the user refresh the page he/she cannot delete post anymore since the accessToken state/context will be null. But if you store it in localStorage, doesn't this defeat the purpose of jwt, because hackers can see it from localStorage. So how do I use JWT, and at the same time, pass down this accessToken if my user refreshes the page?
same problem . did u solve it ?
@@developerbox3079 This is what I saw from someone's post from stack overflow:
1.When you do log in, api sends 2 tokens (Access token, Refresh token) in response to the client.
2.The access token will have less expiry time (may be 15min) and Refresh will have long expiry time (may be 7 or 60 days )
3.The client (Front end) will store refresh token in his local storage and access token in cookies.
4.The client will use an access token for calling APIs. But when it expires, pick the refresh token from local storage and call auth server API to get the new token.
5.Your auth server will have an API exposed which will accept refresh token and checks for its validity and return a new access token.
6.Once the refresh token is expired, the User will be logged out.
@@bingsenlim3121 thank you! I will search more about it
that's because he is giving the token a expiration of 5 sec, put 1d or in miliseconds 86400
Please can you tell at which section of social media tutorial he save user in localStorage. I want to see but unable to find that part.
You are just fantastic
lama please make video on otp and email verification. You have helped us alot thank you so much
Awesome explanation. Thanks.
my brain explode XD ,ty for the great content
best explanation
This is a really straightforward tutorial. Thanks Lama. Is there a reason why we must include "Bearer" in the authorization string?
Is "Bearer "
You can add anything before the access token but it should be separated by space.
eg: BeN .
The concept is to split the value of the key 'authorization' in 2 parts. So after splitting, 'BeN' & '' will come in an array. You have to take only the real token so that it can be verified with the generated one. That's why lama has used
const token = authHeader.split(" ")[1] ;
why you dont use refresh token in ecommerce project.I am little bit confuse with that
Very helpful content thanks👍
Thanks for this great Tutorial...
hey at 23:27 can you explain me what "req.user = user "doing ?
God bless you
thank you sir i was wating for this
super nicely done tutorial
i faced a problem in auth so i am writing this to help other :
if your access token expire after some time then In axios Instance interceptor add "" config.headers["authorization"] = "Bearer " + accessToken; "" because after the token is refresh the axios instance headers will not update automatically .
I Hope i was able to explain what i want to say.
awesome tutorial
i have a question. When i reload the page... it will ask for login credentials again and again.... How do i tackle that?
It would be wonderful if you could use this tutorial on blog project. I really confessed. I can do only Auth . But i can not implement on blog project.
Perfect!!!!!! i will buy u a coofe! cheers from Perú
btw you should make an example like Google auth i mean when you login from other country or device and google send you an alert if you are loggin from there... i hope you can understand thanks!
Thanks for this tutorial
hocam selamlar, ben daha yeni başladım kodlamaya, videonuzu izledim teşekkür ederim sonra, uyguladım kendi uğraştığım bir siteye, access token ve refresh token elde ediyorum. refresh tokenları backende yönlendirdim orada tutuyorum. örneğin bir post atma işlemi yaparken kullanıcının access tokena erişimi olduğunu kontrol ediyor ekstra olarak, backende bakıp refresh tokenlede eşleşme şartı koydum. video başında dediğiniz gibi kullancı 2 nin sadece ismini bulup işlem yapamıyor. yeterli midir basit bir websitesi için
You're gem 💎!
Are you from nepal coz you have name started with lama and here we have lamas and sherpas in himalaya😊
Hi Lama, very appreciate for your tutor, If possible can you teach us how to pass axiosJWT in this video to contextAPI
But, we miss logout from react. How can we stay logged in. Should I store refresh token in browser cookies or local storage
Hi Lama, Thanks for the tutorial. I'm however stuck when logging out. I'm trying to log out by redirecting back to another page but it keeps failing. Kindly assist
thank you ,great tutoriel
Great tutorial thx! For registering, could you show how to implement admin approval needed before users can log in? This way only approved friends can create an account and sign in.
Just create a separate database of 'temp' users to hold registered users waiting for approval. Allow admins to elevate those 'temp' users to 'active' users, moving them to the 'active' database which is the one you would used to sign users in.
Why did you have to put Bearer in the request header value? I don't understand. Why can't we just put the token there without the bearer.
I have a confusion. While logging out since we are only removing the refreshToken and not the accessToken, wouldn't they be technically logged in for the duration of the access token?
yes they would! Thats why you don't keep the duration of accessToken for more than 10-15 mins.
Lama we can't add new lines in the blog description. Can you please see to it?
help, I'm doing this for my website but when user refreshes the page, the status is gone... wtf? Also, what's the point of a refresh token if you only bind it to a specific axios instance. So, if I go afk for 15 mins, I'll still get logged out, unless i delete a user.
Do you have a project to configure interceptors for the entire app?
Why you are using state variable to store the user Data ? Can we store it in cookies/local storage ?
You are the great 👍👍 man
why should we use the word Bearer before the token? , thanks :)
What i was looking for was req.user = user;
awesome video
So with refresh everything will be lost beacuse of the state?
Okay I have a question.anyone help ?
When logging out why do I need to verify?I mean the goal is to delete the refresh token from the array.Its all about the refresh token!
So why bother sending the access token as well??
We did not send the access token when refrshing,,because that was also about the refrsh token!
What do delete user means? If the user is deleted how were we getting the access token with new refresh token even after deleting when we refresh?
i didn't understand "req.user = user", req.user stand for what? in 23:30
here we have assigned new property to req as like req have body , header now req also have user property. I hope u got it
Hi,i tried using it with the blog project i'm stuck.
Could you do the jwt tutorial with the blog project please
Thanks lama
How am I supposed to store the refresh token in my mongo database? should every user have their own refresh token so i call it like 'user.refreshToken' or should they be completely separate from users ?
You can add a new refresh token in users model.
the proxy doesn't work, any advice? :/
Should i save refreshTokens in my User model on mongodb?
Amazing....
Best practice is to store refresh token in an httpOnly cookie
love you so much
Is it possible to store JWT token on Server side not on Client side Cookies???
can you do some MERN Ecommerce tutorial with authenticatiom
so refresh token is only there for refreshing access tokens?
hi, I want that when a person reload page then it still logged in. How to implement this in jwt. I implemented in using local storage but its not good as discussed.
have you figured it out?
@@Ahmadavocado yes. Just simply store the user id and jwt token in local storage. Then u are good to go
@@islamicinterestofficial why not store it in cookuies and enable httponly? localstorage is not so safe
@@Ahmadavocado Its upto you. By the way cookies are also not safe. We're just storing which no one can understand because we only know the key not anybody
Who can tell me why we create a new instance axios please i can't understand that
what keyboard you are using?
Please can some one tell me how to link backend with React?I tried to login many times but nothing happened :(
Thanks man
How can I make the client part tho..