Next.js Discord

Discord Forum

Issue with NextAuth.js Token Refresh and Caching

Unanswered
Sloth bear posted this in #help-forum
Open in Discord
Original message was deleted.

1 Reply

Avatar
Sloth bear
hi, I am facing an issue with NextAuth.js where token refresh and caching are causing unexpected behavior in my authentication flow. When I request a session from the server, the NextAuth.js callback function seems to be triggered twice. This issue becomes problematic when I need to change the refresh token because, during token refresh, it makes two parallel requests to the server. The first request is made with the current refresh token, and upon receiving the new refresh token, the current one is deleted on the server. However, since the second request is sent before the data update, it uses the old refresh token, which has already been deleted, resulting in a 403 error. Consequently, the user is redirected to the login page every 5 minutes instead of getting a new refresh-access token.
first request:

{
refreshToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY0OTJkMzQzOTY2YzhkMDk5Y2E0ZGNmYyIsImlhdCI6MTY5MDEzNDE3MiwiZXhwIjoxNjkwMjIwNTcyfQ.JsIlujWlpjPEFg9umbsR1dxkEUAUsA-UCR9oGyYaJAA'
}
{
newRefreshToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY0OTJkMzQzOTY2YzhkMDk5Y2E0ZGNmYyIsImlhdCI6MTY5MDEzNDE3MywiZXhwIjoxNjkwMjIwNTczfQ.8nbya7vRcIpoNJgKyNF28raHrPDl6hFVxKFwc_Q3Y3o'
}

second request: // it send the old refresh token so then it cause an error

{
refreshToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY0OTJkMzQzOTY2YzhkMDk5Y2E0ZGNmYyIsImlhdCI6MTY5MDEzNDE3MiwiZXhwIjoxNjkwMjIwNTcyfQ.JsIlujWlpjPEFg9umbsR1dxkEUAUsA-UCR9oGyYaJAA'
}
[next-auth][error][JWT_SESSION_ERROR]