nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.23k stars 3.37k forks source link

Session cookie updated in middleware not accessible in server component #11853

Open nphmuller opened 5 days ago

nphmuller commented 5 days ago

Environment


 System:
   OS: macOS 14.6.1
   CPU: (10) arm64 Apple M1 Pro
   Memory: 47.84 MB / 32.00 GB
   Shell: 5.9 - /bin/zsh
 Binaries:
   Node: 20.13.0 - ~/.nvm/versions/node/v20.13.0/bin/node
   npm: 10.8.3 - ~/.nvm/versions/node/v20.13.0/bin/npm
   pnpm: 9.10.0 - ~/Library/pnpm/pnpm
   bun: 1.0.30 - /opt/homebrew/bin/bun
 Browsers:
   Chrome: 128.0.6613.138
   Safari: 17.6
 npmPackages:
   next: ^14.2.2 => 14.2.7
   next-auth: 5.0.0-beta.20 => 5.0.0-beta.20
   react: ^18 => 18.3.1

Reproduction URL

https://github.com/nphmuller/repro-middleware-cookie/commit/d3082fdccb9eb7d18a1a5b817919823681b1ef8b

Describe the issue

When updating the session cookie in the jwt callback (for example when refreshing an access token) using middleware, the updated session cookie is not available in a server component that gets rendered next, resulting in the access token being refreshed twice.

How to reproduce

https://github.com/nphmuller/repro-middleware-cookie/commit/d3082fdccb9eb7d18a1a5b817919823681b1ef8b contains a full repro, but this is the gist:

Update the token in the jwt callback like this: (this simulates a token that is valid for 10 seconds)

     if (
         !token.refreshedAt ||
         addSeconds(token.refreshedAt, 10) < new Date()
       ) {
         console.log("refreshing token....")
         token.refreshedAt = new Date()
       }

Make sure next-auth is called via a middleware (already the default in next-auth-example).

Now run nom run dev and open the main page.

Expected behavior

The console output refreshing token.... should be printed once, but it's printed multiple times.

This happens because the new session cookie with the refreshed token, created in the middleware, is not passed to the server component.

nphmuller commented 5 days ago

Opened PR with an initial solution that works functionally, but I'm not sure if the implementation is acceptable. https://github.com/nextauthjs/next-auth/pull/11854

nphmuller commented 5 days ago

Ah, it seems there was a PR opened already recently with a solution for this problem... https://github.com/nextauthjs/next-auth/pull/11829

EvgeniyKumachev commented 5 days ago

Having same issue

Rikard-Johansson97 commented 3 days ago

I have the same problem also, if someone finds an fix please tag me