How to fix non-effective updateSession of NextAuth JWT
NextAuth is a framework to enable authentication for NextJs, the popular web framework. Among many methods of persisting session, JWT can be used to store session data on users' browsers.
That avoids the bottleneck of having to access a centralized session storage/db. The session data are always available to the request being processed. But updating a session is not as straightforward as server-stored session.
In order to update a JWT cookie, NextAuth relies on the usual HTTP Set-Cookie
header, thus, can only be triggered in a request-response context. As a result NextAuth updateSession
api method is supposed to be called from the client side.
When receiving this request, the [...nextauth].ts
handler invokes the jwt callback to allow for overwriting the jwt data. The response of this updateSession
request is setting Set-Cookie
header to update the browser's cookie.
UpdateSession does not take effect
Sometimes, updateSession does not take effect even though watching from Chrome network tab and server log, the request clearly took place. But intermittently, the browser's cookie got reverted back to its original state. Curiously, this does not happen all the time.
Watching Chrome network monitor, other than the updateSession
request, there is other authenticated api requests to the server at around the same time. And surprisingly, they all have the Set-Cookie
header in response, however, with the cookie value of the cookie sent by the browser when the request originates.
Turned out, NextAuth is setting jwt session cookie for every request that authenticates with it. Not sure if it is a bug or intentional, but as a result, when there are multiple requests other than updateSession
sent from the browser, the session cookie can be overwritten to its previous state due to race condition.
How to fix it
Once we identified the root-cause, the fix is straightforward. set-cookie
header for session cookie should only be present for updateSession
request. For other requests, we can implement a custom middleware to remove NextAuth Set-Cookie response header so that it won't overwrite the result of updateSession