Access token and refresh token in Backend
Вставка
- Опубліковано 10 лют 2025
- Visit chaicode.com for all related materials, community help, source code etc.
Welcome to chai aur code, a coding/programming dedicated channel in Hindi language. Now you can learn best of programming concepts with industry standard practical guide in Hindi language.
github.com/hit...
All source code is available at my Github account:
github.com/hit...
Our Open-Source Project is here: freeapi.app
Join me at whatsapp: hitesh.ai/what...
for community discord: hitesh/ai/discord
Instagram pe yaha paaye jaate h:
/ hiteshchoudharyofficial
HTML video series: • HTML and VSCode - gett...
Complete javascript series: • Javascript for beginne...
Complete Reactjs series: • React JS roadmap | cha...
Javascript and react interview series: • 1 call se shuru hui pl...
Backend development with Javascript: • Javascript Backend Roa...
Thanks to Hitesh Sir, I overcame challenges at my tier 3 college, only because of him, I had no guidance earlier but this man, is the greatest teacher of all time. His teaching style is a game-changer. I've created projects, gained confidence, and salute him. May his influence endure for centuries. Hats off, Sir!
Meri Logic bohot Improve ho gayi hain iss series follow karne ke bad. many many thank you from bottom of my heart .....
can you explain line no 203 in user.controller.js ?
if user is being find out on the basis of decoded token and that decoded token comes from incomingRefreshToken then it finally means user indirectly has been derived from incomingRefreshToken. so what is the need to check if(incomingRefreshToken !== user?.refreshToken) because both refresh token have been derived from user only and hence they both are one in every case.
I have a doubt can any one clarify if the access token is expired we are hitting a route to generate new one but refresh token has more live time than access why again generating new refresh and access both can't we generate only access tokens until refresh expires
@@igssr0 so that duration of refresh token can also long last. Like if it for 2 days then you hit for new access token on 2nd day then it will create new refresh token as well which will continue for another two days.
@@igssr0 this is because to improve security as well as if refresh token also expire we can't generate new access token so we are doing to avoid these problems and remember this is also important for security purposes
i have been following your series from the javascript ,react and now this.. and i can now confidently say that now i know what I am coding, back then use to watch so much of tutorials just to forget it the next day.. but yours teaching approach tends to make me understand why this things are being used from a simple concept of cors to the advance. you have made me understand the core of it. I hope you keep on teaching such valuable resources..
Guruji aapka bahot sukriya, aaysa course quality duniya me kahi or exist hi nhi krta ❤❤❤❤
Making a separate video for this was actually great, awesome!
Right now, you're heartbeat of every 2nd-3rd year student. Hopefully we will complete this project. Thanks a lot sir
no, for everybody knows trying to be a developer.
its a complete package of backend. any course can not have this type of quality. thank you for this sir.
Thank you soo much sir, I'm currently working as a frontend dev in my org and got the opportunity in the current project to almost handle everything be it a frontend, backend or db reports. I was able to understand the things but in backend I do get few dobuts in multiple places while developing the new functionality. But since we've little tight schedules and project is also live so have to handle bugs as well so mostly I fail to clear all my doubts and just wrote the things just to make things work. But after the end of this 16th video I'm understanding most of the things and able to work in backend as well now as easily as I work in frontend. Thanks alot sir for your guidance.
Access points are the key which a suer generated post login .
This is generally of shorted duration . When the session is complete , now user has two options one is to enter the password again and other one is to hit an api end point to refresh token . From both the two, second one is more useful since it is long duration key and can bee refreshed to increase the session and user had not to enter the password manually
AND LOVE TO HITESH SIR 👌👌👌👌❤❤
I have a doubt can any one clarify if the access token is expired we are hitting a route to generate new one but refresh token has more live time than access why again generating new refresh and access both can't we generate only access tokens until refresh expires
@@igssr0 That's a valid question broo
@@igssr0 It is just an implementation or design choice, it is not mandatory to generate a new refresh token every time.. we can simply generate the new access token and keep using the old refresh token until it expires... But generating a new refresh token is considered a good practice for added security...
i am happy ki jo bhi aapne mistakes batayi meri unme se ek bhi nhi thi :)
HItesh sir is mentor and true inspiration for me i come from that background that i can't even finance my livehood and i am studying my diploma in electrical and electronics i watch hitesh sir videos in my 2nd hand broken phone and visit the cyber shop monthly twice and make notes in my notebook and code the project and learning full stack development from chai aur code may this channel growth increase exponentially in 2024 because for sure if he wasn't there i would not be able to learn this much insights of tech thank you very much sir for sure ....
bus aj tak kabi kisi kay saat apnay internal matter share nhi kiye hai aj karnay ka man kara thanks a lot hitesh sir
bus aur kya chai ☕ piyo aur 😭😭😭😭 chil karo
Guruji Dil se sukriya 😅 .iska bahut time se intezar tha😊
Share zrur krna
No cut scene straight forward continue teach us ❤ only hitesh sir can teach us in depth and simple way
hope this might help u :
During login we generate 2 tokens 1) access-token 2) refresh token
we save refresh-token in DB and set access-token and refresh-token cookie in chrome
access-token is for short time and refresh-token is for long time
when user access-token is expired it send refresh token to Back-end
Back-end checks if DB refresh-token and user refresh-token is same or not
if same it generate both token again and repeat process of saving RT in Db and set cookie with RT and AT
@@ahmedsnippet Bhai apne mongoose model wala video nhi dekha shayad usme hi define kiya hai methods schema banene ke baad
Kudos Hitesh! A great series for backend for developers who lack professional experience. One of my friends recommended this series to me for my Full-stack project and I must say you have put a lot of hard work in making this amazing series. Even though, I am using MySQL as the backend for my project, the series was still helpful for code style and logic building. I never felt for watching any other tutorial besides the available docs of the technologies which I used.
While testing my logout route was throwing errors as it could not fetch any token. Upon inspecting, I saw that I was not receiving cookies in login route, which was inturn causing issues with the logout route. So, I commented out the secure option in the "cookie options". And Voila! It worked. Shared it as someone struggling with same issue might find it helpful.
Thanks Hitesh!
Great sir 😊😊. Please continue this series as fast as possible. I have also shared on LinkedIn and to my friends as well. ❤❤❤ Best teacher....🎉❤
4:56 ye line bohaat important hai❤.... mere code ka bug bohaat alag hi tha... took me 55 minutes to solve it 💯👑
Lovinggg the seriess alwayss❤❤❤.. I am a tier 3 college student.. And it really helps me to know how a project is really made and I am going through it and also enjoying😊
Sir, Thank you ki aapne video ko 2 part me rakha. Isme concept clear hogai meri.
I am following your videos on this channel and your English channel now
Not only I have learned JavaScript (in depth), React and now back-end, I have also learned to debug my code properly by reading the errors calmly.
I used to get anxious & frustrated, then quit projects just because of that, thanks for changing my habits
Sir, we can optimize this by implementing middleware. By utilizing middleware, we can exclude the endpoint and efficiently manage the process of obtaining both cookies and updating the access token through the refresh token. This not only streamlines the workflow for the front-end developer but also ensures a smoother experience by handling these tasks seamlessly in the backend.
aisa hi hona chaiye tha thoda unnecessary complicate ho gya
Kamal he AAP ese parhte hn jese hamari confusion hum se sun k clear kr the hon
Access Token - Short lived, not stored in db
Refresh Token - Long lived, stored in db
When access token expires, the frontend sends the refresh token to the backend to validate user (login), once again.
can you please tell me how can i hit that endpoint of refreshToken in frontend? like in what section of frontend i should make a call to that RESTAPI of refreshToken?
I think in third line u meant access token instead of refresh token because, when access token expires how can frontend send refresh token which is in backend send to backend??
@@ShreyanshGajjar-k1s ig when access token expires after a certain period of time, we have to hit the endpoint of API which will match our refresh token with the refresh token stored on db and again generate a new access and refresh token.
@@ShreyanshGajjar-k1s because accessToken is already saved in cookies of front end . Whe front end send cookies to server then server will check incoming refreshtoken with refresh token stored in database
i also have same question if refresh token is also new generated with acess token then whats the point of givng longer expiry time to refresh token
before getting into industry it was the good playlist , after getting a job and doing some work now realized , It's the BEST !!!!
sir please continue this series , i am studying very seriously
Itne detailed me koi nahi padhata h even paid course me bhi nahi koi padhata sir. Hats off for your hardwork❤ lots of support.
subscribers are increasing around 1K per day 😮😮
Sir with much RESPECT, you are an amazing teacher and personality. SHUKRIYA itna achay parhanay k liay and SHUKRIYA itna acha (quality content) prhanay k liay.❤
At 22:07 Only generate new access token don't generate refresh token again as it is already long lived and while sending back cookies send new access token and old incoming refresh token. Still if you want to generate both the tokens and send them back to the frontend then make sure that you save the new refresh token in the database . Otherwise there is no use of keeping long lived refresh token. I think sir might have missed this point while recording.
I have a doubt. We didn't updated the refresh token and access token in DB, this might cause error . Correct me if am wrong.
@@vishakhakhanna8115 we will update the refresh token in DB if and only if both refresh and access token have expired.
If only acces token has expired then in the backend we will check whether the refresh token, coming from the frontend is same as the refresh token in the DB and has not expired, then we only generate new access token in the backend and send it to frontend.
Note that in DB we only store refresh token and not access token.
You are wrong here. Because when we call generateAccessTokenAndGenerateRefreshToken() .there is already code for saving refresh token in DB. so whenever we call generateAccessTokenAndGenerateRefreshToken() it will automatically save new refresh token in DB
@@husain6213 Thanks, got it!
@@husain6213 True , But what point of generating refresh token again with access token.
14:32 Sir in user.controllers.js in refreshAccessToken function in line no. 188. you miss to put "!" In if condition-
Mistake -
If (incomingRefreshToken) {
Throw new ApiError(401, "unauthorized request")
)
Fix -
If (!incomingRefreshToken) {
Throw new ApiError(401, "unauthorized request")
)
This is fixed by sir
thanks for the video.
refresh token ko samajna pehle difficult tha, now I have understood.
Hitesh Sir, when we are using asynchandler() which already have try and catch block then why we are using another try and catch block inside refreshAccessToken() function when it is also wrapped with asynchandler() func??
Same doubt bro🤝
first time solved bug without taking help of chatgpt and stack overflow on access token and refresh token mene arrow function use kara tha jabki normal function use karna tha due to problem with this keyword uski wajah se token generate nhi ho rha tha.. all thanks to you sir, i usually dont comment but aapko salute hai!!!
hey i am facing the same error
thanks sir , quality + teaching style is unparalleled .
I remember when I was trying to learn redux and other YT videos are very confusing their ,then the video on redux of hitesh sir came then the concept of redux became very easy for me
Thank you sir ache se samjh agya refresh and access token
Kuch mahine pahale mai Linkedin ki api se kuch develop kar raha tha, usme bhi kuch refresh aur access token ka scene tha. Access token to pata tha but ye refresh token wala concept mujhe to bilkul samj nahi aaya tha tab.
Ye video dekhne ke baad aur khud code karne ke baad clear hua hai concept 😌
Thanks sir now you are one of the greatest teacher in you tube community and this course is much more better than paid courses 🙏🙏🙏
This course in very enjoyable learning with chai and code
series bohat pasand arhi he. thank you sir!
thanks sir for your hardwork for the students to providing the quality and production leevel
content
Best video on this topic...🤗
Sir you already finish this series
But I am learning from it now
Thank You so much
Right now I completed hitesh sir JavaScript series and starting react❤
thanks sir , quality + teaching style is unparalleled .
Awesome content, really like how the things are connected and dependent on each other in backend. Frontend + Backend = 🔥🔥. Thankyou sir for such content.
I really follow your video and implement in my day to day its very helpful for me to write clean and production ready code
Your are really mentor my coding jauarny❤❤❤🎉
i had spend 3 hours on previous video just to figure out how everything was working like cookies , accessToken, refreshToken , etc
how a refresh token added to our userInfo documents when it logs in
how it removes the refreshToken property from the document when it logs out
how if we didn't give authorization headers from postman it was still logging out (this thing confused me for a long time then i did some Console.log all over our code and after that i figured out that postman was also sending the cookies with out post logout request... i guess)
but afterall it was really fun
This whole series is Amazing Thank You Hitesh Sir
Am lovin the series. learning backend from an industry standerd level.
Thank you sir for providing a clarity, the difference is cleared now
thanks sir , quality + teaching style is unparalleled . ❤
This Series helped me a lot with errors when earlier I use to get error I was scared of them didn't know how to handle them and even how to approach an error. Today while I was checking Login page I got couple of error first was password was incorrect, checked my DB it was not encrypting the password went through all the code and didn't wrote an await in a single line that caused the error. few others were I wrote user instead of User when trying to find the id, thanks a lot For building my confidence with your explanation and deep dive into topics
Thank you Hitesh sir for this series , the knowledge you are providing us is very precious (Gulabi Dil)
Best video explaining about the refresh token and access token
Now I can find out the solution of the errors step by step .. thank you so much sir ❤️
Thanks Hitesh Sir, I am here to refresh my concepts for Production based projects. I am regaining my confidence back.
Thanks a lot.
One of the best playlists on javascript backend
Thanks
great teacher comes with great videos 😊
First I watched the videos learns a bit this and that, then I code without video sometimes refer to github repo and do it in typescript then now rewatching to look if I've missed something else or any assignment
Lovely series sir
While doing this I already got so many project ideas and this series will be base of all that
great videos sir please make this series complete there will be non of other videos compare with this series at all Time Top no matter people is likeing or sharing or not but getting involved in it that is most important impact of this videos.. Make and completed it
Love from Kiran to Chai aur COde 💖💖
The video may be brief, but its content is impactful and truly impressive.
keep posting videos quickly sir its an amazing series i follow every thing the first day only
Jldi to humse nhi ho paata, apna safar relax hoke hi chalta h
Great serese sir, please continue rakhiye ise...bech me stop mat kijiye....😢
No sir don't stop this series the only hope you are all over the youtube so don't stop this series sir please it's humble request 🙏
First of All Thanks Hitesh Sir, and I just want to say that, the ease with which you explain the concepts that too in great detail is just amazing.
when hitesh bhai said sabko kuch nahi aata he sab idahr udhar se dekh ke kar rahe he thoda logic use kar rahe he nahi aaraha he to fhirse check kar rhae he... this line gave me confidence, as I am started to feel like in all this technology advancement I am still, in stone age 😭
thank you for the separate access toekn and refresh token video
sir your teaching skills is next level please don't stop keep moving forward and continue this series i learned Node js from this course THANK U SO MUCH SIR >>>>>
Sir, this series is just mind blowing and totally love your approach to teach us every topic❤... Please continue ki jiyega iss series ko end tak, bohat helpful hai, aur maza aata hai sikhne mein aapke sath
Wooow great teacher comes with great videos 😊
Thanks for the video sir 😊
it really helps me to know how a project is really made and I am going through it and also enjoying😊
Thank u so much for providing us in depth knowledge 🙏🙏🙏🙏
complexity me hi mazzaaaa hai. 😍😍😍😍😍😍
Backend seems to be so easy just because of you only. Before your videos, our opinion about backend was "it a very complex tech and it need a lot of complex algos for doing every tasks" and now our opinion is " backend is just a normal logic with some js packages and a bit of production grade standerds"
Hitesh sir is god for me❤️❤️
Real teacher ❤️
I have no money to read computer engineering so i am reading commerce
But i am interested in technology and software engineering
So i am reading it from online
By Hitesh sir I am learning coding full stack from his UA-cam channel❤❤🎉
Same bhai👍 keep growing bro
I am at the series dedicatedly. But i came here into this video for full-fill our commit by commenting your video
Thank you so much Hitesh sir, for making such an amazing series.
This series not just a series, this is backend university, we just loved it ❤🔥❤🔥❤🔥❤🔥
Sir Thank you so much for bringing this high quality content. Please sir continue it 🥰🥰🥰
finally ab samjha refresh token ka use
Sir badiya series hai
Continue karte rahiye sir...
sir is more sucessful still more hardworking than me!!😊😊
You explained it so simply, lot to learn from you apart from your coding
bhaut in depth video hai sir thanks for the video sir
I am learning so much from this series thank you hitesh sir!!!
I am addicted to this channel
thanks and love you sir for your valuable content💖💖☕☕
Thank you sir for this amazing session on accessToken and refreshToken
😇 mindBlowing Hitesh sir
thanks sir
This content is awesome as always! Sir your teaching style is great!
Amazing explanation sir. Kudos 🙌 to your simple style of teaching. Hope to meet you soon sir❤
I learned alot from this series worth watching👍
Amazing backend series I ever seen 🎉
i have learned backend a lot and always dreamed to make industry level code now i can
this is unbelievable content!
Toal Worth it Each and evry second of full course
thank you so much hitesh sir, i was getting a lot error but i solved that myself by doing console log and by understanding the error problem, and after solving i thought i did something supercool thing! 😃😃
Awesome Playlist Sir, Thank you !!
Very good videos