Refresh Token Rotation With Next-Auth V5 || Managing Tokens With A Custom Backend

  Рет қаралды 7,178

tapaScript by Tapas Adhikary

tapaScript by Tapas Adhikary

Күн бұрын

Пікірлер: 86
@xeom
@xeom 2 күн бұрын
I've been grappling with this issue for a long time, and your video finally provided the solution. Thank you so much for your clear and insightful guidance. keep it up Sir!! From VN
@nathancho4037
@nathancho4037 2 ай бұрын
this is the most clear guide ive ever seen. it would be much greater if you handle TS in this guide but whatever i can take care of that myself. thanks! love your video
@tapasadhikary
@tapasadhikary 2 ай бұрын
Thanks a lot ❤️
@hichamgr3152
@hichamgr3152 Ай бұрын
GREAT CONTENT! i watched all the next auth series as they were excellent, but is there anyway to make a video where you push the access token auth further using jwt User Roles for RBAC ?
@MahfouzTeyib
@MahfouzTeyib Ай бұрын
Wow keep it up Sir!!
@tapasadhikary
@tapasadhikary Ай бұрын
Thank you 🤩
@imkir4n
@imkir4n 3 ай бұрын
thank i asked about this at the beginning of the series.
@tapasadhikary
@tapasadhikary 3 ай бұрын
@@imkir4n I know 😀. Glad to help now.
@imkir4n
@imkir4n 3 ай бұрын
@@tapasadhikary yeah. A suggestion maybe you can add 'with a custom backend on title' there is no content out there with a separate backend.
@tapasadhikary
@tapasadhikary 3 ай бұрын
@@imkir4n Great suggestion.. updated.
@utsavmaji4798
@utsavmaji4798 Ай бұрын
Thanks sir, This video saved me
@tapasadhikary
@tapasadhikary Ай бұрын
Glad it was helpful ❤️
@SLCricket-io6qi
@SLCricket-io6qi 2 ай бұрын
very very thanks sir💗
@tapasadhikary
@tapasadhikary 2 ай бұрын
❤️❤️
@mdsumonh.shohan9159
@mdsumonh.shohan9159 Ай бұрын
I want to learn nodejs backend do you have any suggested YT playlist?
@kunalrathor7114
@kunalrathor7114 2 ай бұрын
thanks sir , learn a lot can you make one video more related to cookie based Auth, ( accessTOken and refreshTOken are in cookie)
@tapasadhikary
@tapasadhikary 2 ай бұрын
Sure, thanks a lot.
@milesrykerodazie171
@milesrykerodazie171 3 ай бұрын
this is a really great video.thanks for this.i want to ask can this refresh token rotation be done using cookies instead of sending the access and refresh tokens in the response from backend?
@tapasadhikary
@tapasadhikary 3 ай бұрын
Yes very much but remember Next.js does not allow modifying the cookies from the client for the security reason... so even if you have to handle it through cookies, it has be on the server side only.
@milesrykerodazie171
@milesrykerodazie171 3 ай бұрын
@@tapasadhikary thank you so much this helped.
@neerajrathore
@neerajrathore 3 ай бұрын
Awesome 💯
@tapasadhikary
@tapasadhikary 3 ай бұрын
Thanks 🔥
@sameedahri3939
@sameedahri3939 3 ай бұрын
Best video brother, you just saved me
@tapasadhikary
@tapasadhikary 3 ай бұрын
Thanks man, thanks a lot. Glad to know.
@sameedahri3939
@sameedahri3939 3 ай бұрын
@@tapasadhikary can you please share the font name used in VSCODE
@sameedahri3939
@sameedahri3939 3 ай бұрын
I have one issue also, my refresh token work well in first time but not work in second time, because JWT still saved the old token :/ can you please help. I am using same versions as you used in tutorial
@tapasadhikary
@tapasadhikary 3 ай бұрын
​@@sameedahri3939 That's weired. JWT will not save the old access token... asin it will not save but it will use. You need to programmatically refresh it only when it expires. It could be with the logic in the code...As you have seen in the video tutorial, the jwt callback always check for the expiry and everytime it expires, we were forcefully refreshing. So I would suggest you to check in two places: - The expiry of the access token. - The logic to check the expiry and refreshing the token. All the best!
@sameedahri3939
@sameedahri3939 3 ай бұрын
@@tapasadhikary Thanks for your reply, I still having the same issue, because token is not updated after refresh call, because Next JS doesn't allow to modify cookie while it is rendering. I am curious how your code is working :D
19 күн бұрын
can we do that same with prisma neon or superbase
@dev-akeel
@dev-akeel 29 күн бұрын
15:55 Why a new refresh_token? I got it that the access_token is short lived and has expired but I am unable to understand the logic behind getting new refresh_token. This might make the refresh_token expiry as infinite ♾️??
@ItsKrishnaPanthi
@ItsKrishnaPanthi 2 ай бұрын
Was waiting for callbacks handling jwt and session. Thanks for the in depth explanation. Any particular reason for not including login and refresh end points in the source code?
@tapasadhikary
@tapasadhikary 2 ай бұрын
Thank you! No reason other than making it available as part of the MERN videos to create a Node Express based auth endpoint... Will make the code available also along with it.
@supersanjay666
@supersanjay666 15 күн бұрын
I have a query what if the refresh token expires. will it automatically logout or we have to write some logic to check if refres_token expires should redirect to /auth/signin?
@tapasadhikary
@tapasadhikary 15 күн бұрын
We should have the logic written for it. It will not be automatic here.
@petursteinn9718
@petursteinn9718 2 ай бұрын
Can you address how to deal with race conditions? When two parallel requests come in, triggering jwt callback at the same time and they get new sets of refresh tokens seperately
@LouisNgatale
@LouisNgatale Ай бұрын
Did you find a way around this, as I've been struggling with this, since my approach is, refresh tokens should be invalidated/blacklisted upon re-freshing, so in case of race conditions, This causes mayhem
@RitikRaj-we2sc
@RitikRaj-we2sc 2 ай бұрын
hello sir, I am facing an issue with session expiry. It would be great if you could help me out. Thanks I have a Navbar (server component) that is part of my layout. And I render links like "Login" and "Logout" in the Navbar based on the session using getServerSession(). The problem is that when the session expires and I navigate around the app, my route handler redirects me to the / route using the redirect() function from next/navigation. However, the Navbar state doesn't update to reflect the expired session. How to handle this ?
@alexdin1565
@alexdin1565 2 ай бұрын
thanks , what if the user login using a provider ? the tokens and refresh tokens are same thing or what? please make deployment with docker
@tapasadhikary
@tapasadhikary 2 ай бұрын
It is similar in that case too.. in fact auth.js doc has a example with Google Provider you can check out. I have done a deployment of it on vercel front end and render the API portion.. Haven't tried the docker yet.. will surely make when I give a hand on it.
@ayushshende4290
@ayushshende4290 2 ай бұрын
What changes are needed in the nextjs code if the server sends http-only cookies (access and refresh) and we don't want to use next-auth ?
@TechWarriorzOfficial
@TechWarriorzOfficial 24 күн бұрын
Saved me!!! Brooooo
@tapasadhikary
@tapasadhikary 24 күн бұрын
@@TechWarriorzOfficial you are most welcome
@karemelshendy-8945
@karemelshendy-8945 2 ай бұрын
thank you for amazing video , what the extension for console.log preview
@tapasadhikary
@tapasadhikary 2 ай бұрын
Thank you! The extention name is console ninja
@justin9494
@justin9494 3 ай бұрын
THANK YOU SO MUCH
@tapasadhikary
@tapasadhikary 3 ай бұрын
Most welcome
@soulfly9306
@soulfly9306 3 ай бұрын
Should i type if else catch after every request to check my token has expired I think this is bad idea. What do you suggest instead of this ?
@tapasadhikary
@tapasadhikary 3 ай бұрын
No you do not need to... check other way instead.. check if the token is still alive then continue to use it... if not, return the refreshed token. That way code will be lesser. Also, you do not want to throw an exception is token expired as we are rotating it instead. I hope it makes sense.
@imrancse94
@imrancse94 3 ай бұрын
Hi Tapas da. How can I update session according to api response value in lib/fetch-client.js? Is there any way for it?
@tapasadhikary
@tapasadhikary 3 ай бұрын
For that only we have the session callback, vai. Whatever you need to add to the session or update, do it in the session callback. Session callback has got all the information from the jwt callback for you to update. Also remember, session is just an object, you can even add your own data to it.
@abdurrahman720
@abdurrahman720 3 ай бұрын
I was working on a company (building e-commerce site) and faced this custom backend token rotation issue with nextAuth v5. I had to go through a 'bangla' system to manage the issue and for more secured api, I had to use the native nextjs api as well as the server action. eagerly waiting for this! maybe there is no other solution on youtube on this regard! thanks
@tapasadhikary
@tapasadhikary 3 ай бұрын
Thanks! I just deployed the entire solution on Vercel, Render, and MongoDB Atlas.. it works like a charm.
@ParthPatel-n6l
@ParthPatel-n6l 2 ай бұрын
which font do you use in vscode can you please share?
@tapasadhikary
@tapasadhikary 2 ай бұрын
Lws, Operator Mono
@loznicafk
@loznicafk 26 күн бұрын
nice one, but session callback doesn't return what you put in it.. it always return the default obj
@tapasadhikary
@tapasadhikary 25 күн бұрын
The session callback gets the session object along with the user and token information. So we can set the information on the session object and return. It helps you to pass the data to the browser and make it available there on the client.
@Rajesh-rg6fw
@Rajesh-rg6fw 2 ай бұрын
Extremely informative. But I don't think this is the better way of doing this. What i do most of the time store the refresh token in the db, and only share the access token to client on secure cookies. So everytime i dont have to send it again and again, by default the cookies will on every request. If it expired then got 401 and based on that again a request to backend for token rotation. Don't u think this a better way of doing this?
@郭海杰-f8y
@郭海杰-f8y 18 күн бұрын
如何在API里面获取到session内容(用户信息 id等)
@tapasadhikary
@tapasadhikary 18 күн бұрын
Use the auth() function to get the session object const session = await auth()
@sashirkl
@sashirkl Ай бұрын
Sir kuch suggestion Dena chahta hoon. Aapka video acha hai but kuch kami laga mujhe . Yeh Mera personal view hai. Sir thoda slow chaliye. Har video mein ek agenda sheet dikhaiye ki what exactly u want to deliver. English ko thoda slow and pause leke boliye . Awaz thoda tremble kar raha hai . Video editing mein usko thoda adjust kariye . Har topic ek real project mein kahan fit hota hai thoda bataiye. Matalab Kahan hai aur kya achive karna hai .
@tapasadhikary
@tapasadhikary Ай бұрын
Thank you for watching my videos and your interest in learning from them. Some of your suggestions are great, I will bring them in my future videos wherever they are relevant. Keep learning.
@xardasu3646
@xardasu3646 12 күн бұрын
Why is that when I refresh token the first time , I got the tokens updated. The moment I refresh again it returns older token. It seems that cookie not updated in the client. I think I already follow your code.
@DaviReisVieira
@DaviReisVieira 2 күн бұрын
I have the same problem. Did you find how to solve?
@xardasu3646
@xardasu3646 10 сағат бұрын
@@DaviReisVieira not yet. clueless right now.
@alexdin1565
@alexdin1565 2 ай бұрын
in your code, if you refresh the page before the token expires the refresfToken function calls again if you deploy this app and you have many users refreshing the token on every request this will hurt your server
@tapasadhikary
@tapasadhikary 2 ай бұрын
Yes, good point. I think it will be persist the refreshtoken in a store or something like that like an array of tokens for user and issue that? Do you suggest any other solution for that?
@normydev
@normydev 2 ай бұрын
@@tapasadhikary Didn't get that how the `refreshAccessToken` will get executed on every request. The code already has the expiry check and if the token is not expired then it should not call `refreshAccessToken`, isn't it?
@jubayer-ahmed46
@jubayer-ahmed46 3 ай бұрын
🎉 20k
@tapasadhikary
@tapasadhikary 3 ай бұрын
@@jubayer-ahmed46 wow, yeah ❤️, thanks 🙏
@manualchnn
@manualchnn 2 ай бұрын
I think this process has some issues as if the flow is based on cookies, the cookie is not updated so once the token is expired its going through the refresh token process everytime. I think this is an issue as the cookies are not updated after each rotation. Any idea how to sort it out?. You can check this in your video at 46:10 when you hover you can see the log is executed update refresh token multiple times. Ideally the cookie should be updated, otherwise once its expired it is going to call refreshToken all the time.
@tapasadhikary
@tapasadhikary 2 ай бұрын
There seems to be an open issue already with auth.js about the rotation, hoping it gets resolved github.com/nextauthjs/next-auth/issues/7558
@MahinKhan-s2h
@MahinKhan-s2h 3 ай бұрын
sir bangla video chai
@tapasadhikary
@tapasadhikary 3 ай бұрын
In Bangla channel :-)
@Etymologicult
@Etymologicult 2 ай бұрын
Great tutorial on implementing Auth.js beta 5 with Next.js! I have a few questions about some aspects of the implementation: - Refresh Token Handling: In the refreshAccessToken function, an error is returned when the refresh fails, but it's not clear how this error is handled downstream. How would you recommend dealing with invalid refresh tokens in the jwt callback or elsewhere in the auth flow? I have a python backend handling the token and other routes and I am not sure how to correctly handle that - Potential Redirect Loop: In the user page, there's a check for a 403 status that redirects to the login page. However, if Auth.js still considers the token valid, couldn't this create a redirect loop? How would you suggest preventing this - maybe by clearing the session before redirecting ? Thank you!
@tapasadhikary
@tapasadhikary 2 ай бұрын
Thank you for your comments. Glad you liked it. Here is how I am thinking of the scenarios: - The best way to handle the error from auth,js(this is what I found so far) is by throwing the custom exceptions from the error prone places. Now in most cases the invocation point of the calls would be either from a Server component, Client Component, or Server Actions. We can catch and treat the errors these ways: a) Server Component: in error.js by checking for the exception type b) Client Component: Some kind of toast message by checking the exception type c) Server Action: Rethrow it from a try-catch and catch it again in either of the above a or b cases. Let me know if you want to add anything to this approach. Would love to discuss and learn. - Cleaning the session before redirecting seem to be a good solution. Thanks!
@Etymologicult
@Etymologicult 2 ай бұрын
@@tapasadhikary Thank you for your response! I will try different options to see which one could be the best
@Etymologicult
@Etymologicult 2 ай бұрын
So here is what I am doing currently (not sure I am 100% happy with it) Refresh Token Handling: In the jwt callback, I attempt to refresh the token when it expires. If refresh fails, I an error flag: {...token, error: "RefreshAccessTokenError"}. This error is then passed to the session in the session callback. Error Handling in Auth Flow: I am using authorized callback checks for the RefreshAccessTokenError (I am doing every logic here not in the middleware file itself) If detected, it redirects to the login page with an error parameter. This approach allows the login page to display an appropriate error message and to sign out the user. Preventing Redirect Loops: The authorized callback includes checks for different route types (API, public, auth). For auth routes, even with a RefreshAccessTokenError, it returns true, preventing loops. For other routes, it redirects to login with the error parameter. This works perfectly, there's one scenario that needs attention: If a user with an errored session navigates directly to `/login` (without query parameters), they can access the login page without seeing the appropriate error message. I didn't find an appropriate answer for that with the current logic
@soumyajeetdas5339
@soumyajeetdas5339 14 күн бұрын
The backend code would have been more helpful
@pratiksavaliya3890
@pratiksavaliya3890 2 ай бұрын
I don't think this is how it should be implemented...it seems like you are embedding third party server token in authjs token so there are two types of access tokens now in your system.
@OnlyJavascript
@OnlyJavascript Ай бұрын
How is it done??
@pratiksavaliya3890
@pratiksavaliya3890 Ай бұрын
@@OnlyJavascript as far as i know there is no official way of doing credential login with authJs and third party server ....i have searched and tried but didn't found the way yet.
@rahulk143
@rahulk143 Ай бұрын
I do like to know your approach. If you are having a dedicated authentication api server and use it in react/next like old fashion. How can we able to do with next auth.
@pratiksavaliya3890
@pratiksavaliya3890 Ай бұрын
@@rahulk143 i am also trying to find the same solution but seems like next auth only works for full stack nextjs projects.and not with dedicated auth server
Next.js Error Handling Patterns || Common Mistakes To Avoid
41:54
tapaScript by Tapas Adhikary
Рет қаралды 2,2 М.
Sigma baby, you've conquered soap! 😲😮‍💨 LeoNata family #shorts
00:37
ЛУЧШИЙ ФОКУС + секрет! #shorts
00:12
Роман Magic
Рет қаралды 21 МЛН
Ouch.. 🤕⚽️
00:25
Celine Dept
Рет қаралды 33 МЛН
Next.js Middleware Crash Course || App Router Protected Routes
1:01:02
tapaScript by Tapas Adhikary
Рет қаралды 10 М.
Full Stack Authentication With Next.JS | Next Auth | Nest.JS
1:33:47
Next.js Authentication || Register User To MongoDB With Next-Auth V5
35:23
tapaScript by Tapas Adhikary
Рет қаралды 11 М.
I DONT USE NEXT JS
54:01
ThePrimeTime
Рет қаралды 373 М.
What Makes A Great Developer
27:12
ThePrimeTime
Рет қаралды 205 М.
Set up Next-Auth with Next.js and Prisma with this ultimate guide!
42:45
Build SaaS with Ethan
Рет қаралды 56 М.
What Is An API? And How It Works! A Simple Explanation 😆
28:16
tapaScript by Tapas Adhikary
Рет қаралды 1,9 М.
NextJS, NextAuth with App Router and Keycloak (Demo part 3/3)
40:36
Next.js Server Actions || Learn Patterns & Project Building
1:00:22
tapaScript by Tapas Adhikary
Рет қаралды 4,4 М.
Sigma baby, you've conquered soap! 😲😮‍💨 LeoNata family #shorts
00:37