Next.js Discord

Discord Forum

NextAuth.js v4 - JWT callback triggering numerous times

Answered
Jersey Wooly posted this in #help-forum
Open in Discord
Jersey WoolyOP
Versions :

NextJS: 14.0.4
NextAuth.js: ^4.24.5

Hi, I have a problem in my application where I've set up JWT authentication with refresh and access tokens from my own external API. Currently, everything is working fine except for one thing – each time I access a page, the JWT callback is triggered numerous times. The issue lies in this callback function, where I'm also handling the refresh token fetch call to my external API. It gets called numerous times, causing the JWT refresh token to become obsolete on the front end and requiring users to log in again. I've been trying for a few days to find a solution to this problem. Has anyone faced a similar issue, and how did you resolve it?
Answered by Jersey Wooly
To fix my problem I memoize the refreshToken function using [memoize package](https://www.npmjs.com/package/memoize?activeTab=code) with a delay of 60 seconds to be sure that the session has the time to get the new tokens and to avoid getting multiple refresh calls that invalidate my refresh token and forcing the user to log in again,
View full answer

4 Replies

Jersey WoolyOP
Example of logs when Im login in and being redirected after login
[Wed, 24 Jan 2024 16:19:15 GMT] First login
[Wed, 24 Jan 2024 16:19:15 GMT] JWT callback
[Wed, 24 Jan 2024 16:19:15 GMT] Actual token exp 1706113335
[Wed, 24 Jan 2024 16:19:15 GMT] Time remaining on token : 179172
[Wed, 24 Jan 2024 16:19:15 GMT] Session callback
[Wed, 24 Jan 2024 16:19:16 GMT] JWT callback
[Wed, 24 Jan 2024 16:19:16 GMT] Actual token exp 1706113335
[Wed, 24 Jan 2024 16:19:16 GMT] Time remaining on token : 178776
[Wed, 24 Jan 2024 16:19:16 GMT] Session callback
Jersey WoolyOP
Depending of the page im accessing, I can get one or multiple sessions and jwt callback calls
Jersey WoolyOP
To fix my problem I memoize the refreshToken function using [memoize package](https://www.npmjs.com/package/memoize?activeTab=code) with a delay of 60 seconds to be sure that the session has the time to get the new tokens and to avoid getting multiple refresh calls that invalidate my refresh token and forcing the user to log in again,
Answer