Help me with Refresh Token Rotation on Next.js 15 #77558
Replies: 6 comments
-
so how much time did you optimize by using your code instead of middleware |
Beta Was this translation helpful? Give feedback.
-
I ended up using only an access_token to get my session. |
Beta Was this translation helpful? Give feedback.
-
Nice job. |
Beta Was this translation helpful? Give feedback.
-
As I was using JWT and refresh token to, in the end, get the user session, I've simplified the job. |
Beta Was this translation helpful? Give feedback.
-
hmm.. looks good but let me think |
Beta Was this translation helpful? Give feedback.
-
I can’t believe I might need to migrate my entire dashboard to plain React just because it seems impossible to implement basic JWT auth with rotating refresh tokens. I’m reaching a point where I no longer know if it’s me who doesn’t know how to do it, or if the framework is really that limited. I can’t believe nobody else needs this basic feature. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
What I want
I am developing an app in Next.js 15, and for authorization, I want to use JWT and Refresh Token, following this process:
access_token
cookie (a JWT with a validity of 7 minutes), which contains theiruserId
, and verifies if it is valid.refresh_token
cookie (just a token with a validity of 7 days) and:userId
, recreates both theaccess_token
(JWT) and therefresh_token
, updates the cookies, retrieves the user session, and continue.The problem
The issue I'm facing is with this Refresh Token Rotation:
When accessing the page (e.g.,
app/dashboard/page.js
), I can read the cookies for verification, but I cannot update the cookies because they can only be "written" via Server Actions or Route Handlers.UpdateAccessCookies
) to place on the page that would solely be responsible for sending the cookies, but doing this causes the system to enter a loop.Here are some example codes
As I mentioned, I have already tried updating the cookies:
getCurrentSession
(would be ideal)What would you suggest?
Note: I don’t want to use an external library. I also don’t want to perform verification using middleware because it would check on every request to restricted pages, which would significantly increase request time.
UPDATE
I've manage to make it work changing a little bit, the logic on the Refresh-cookies.js (above), now it looks like this:
Now it updates the cookies: 1. if it received a refreshToken (in which case the 'access_token' was invalidated or expired) OR 2. if it received a JWT and the cookies aren't yet updated.
This way it doesn't get on a loop.
What do you guys think?
Beta Was this translation helpful? Give feedback.
All reactions