next-auth
next-auth copied to clipboard
SessionProvider sends many requests to retrieve the session
Environment
System:
OS: Linux 6.1 NixOS 23.11 (Tapir) 23.11 (Tapir)
CPU: (12) x64 12th Gen Intel(R) Core(TM) i7-1255U
Memory: 8.62 GB / 15.34 GB
Container: Yes
Shell: 5.9 - /run/current-system/sw/bin/zsh
Binaries:
Node: 21.6.2 - ~/.nix-profile/bin/node
npm: 10.2.4 - ~/.nix-profile/bin/npm
pnpm: 8.15.3 - ~/.nix-profile/bin/pnpm
Browsers:
Chromium: 122.0.6261.94
npmPackages:
next: 14.1.2 => 14.1.2
next-auth: 5.0.0-beta.15 => 5.0.0-beta.15
react: ^18 => 18.2.0
Reproduction URL
https://github.com/srinesha/nextjs-testing
Describe the issue
I have setup credential provider authentication. When SessionProvider
is added in the layout, one page reload sends around 5 requests to retrieve the session even though useSession is never used anywhere in the application.
SessionProvider in layout.tsx: https://github.com/srinesha/nextjs-testing/blob/ec5d831cd926fd86f9f0b1952df91829034ba4c3/app/settings/layout.tsx#L10C1-L14C23
https://github.com/nextauthjs/next-auth/assets/160213066/6a1e2bc1-77fc-4159-9088-82b37bd4ded0
How to reproduce
https://github.com/srinesha/nextjs-testing
- Clone the repository
- Install dependencies
pnpm install
- Run
pnpm dev
- Go to
localhost:3000/auth/login
- Enter any random email address
- Click on submit
- When loading the settings page, there will be many requests to get the session
Expected behavior
Send one request per page load?
<SessionProvider
refetchOnWindowFocus={false}
refetchWhenOffline={false}
session={session}
>
{children}
</SessionProvider>
Also, if the app is running in multiple window on same browser each window will send a revalidation request to the api. it sends a broadcast to each window for revalidation.
Same, no workaround helps, I always get three /api/auth/session
calls when session refetch happens. Version 5.0.0-beta.16
on Next 14.1.4.
Can confirm: three session requests per app load.
Still present in beta.17
From what I understand, there are two bugs that cause unnecessary /session
requests.
-
broadcast().postMessage(...)
andbroadcast().addEventListener(...)
work on differentBroadcastChannel
instances within the same window, which means that messages that are intended for other windows are also handled by the same window. In consequence, every session update that is broadcasted also causes another session update within the same window. - When working in development mode, React runs every effect twice. The broadcast effect runs
broadcast().removeEventListener(...)
for cleaning up in between, but sincebroadcast()
alwass returns a newBroadcastChannel
instance, no listener is removed and we end up with two instances with listeners that callgetSession
for each session update.
I fixed both in this PR: https://github.com/nextauthjs/next-auth/pull/10762
I can confirm that the issue was resolved in beta.18
for us.
This was indeed fixed in #10762, great research and PR by @luchsamapparat! :green_heart: