nextauthjs / next-auth

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

Make broadcast channel a singleton to prevent unnecessary `/session` requests #10762

Closed luchsamapparat closed 2 weeks ago

luchsamapparat commented 2 weeks ago

☕️ Reasoning

Usually, posting a message to a BroadcastChannel should not trigger the message event within the same window. However, if there two (or more) BroadcastChannel instances within the same window, posting on one instance triggers the message event on all other instances.

Wrapping new Broadcast("next-auth") in a broadcast() function means that every broadcast().postMessage(...) call is done on a new instance. As a result, the message event listener, which sits on a different BroadcastChannel instance, calls __NEXTAUTH._getSession within the same window - even though postMessage was probably called by a getSession call in the first place.

Also, broadcast().removeEventListener(...) in useEffect does not have any effect since it isn't called on the BroadcastChannel instance on which addEventListener has been called. In React's StrictMode all effects run twice in development, and since the unsubscribe isn't working, there are two event listeners firing for each message event.

🧢 Checklist

vercel[bot] commented 2 weeks ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
auth-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 29, 2024 2:35pm
1 Ignored Deployment | Name | Status | Preview | Comments | Updated (UTC) | | :--- | :----- | :------ | :------- | :------ | | **next-auth-docs** | ⬜️ Ignored ([Inspect](https://vercel.com/authjs/next-auth-docs/2eSitnQza3r1zs6K36XkNhUaHBDZ)) | [Visit Preview](https://next-auth-docs-git-fork-luchsamapparat-main-authjs.vercel.app) | | Apr 29, 2024 2:35pm |
vercel[bot] commented 2 weeks ago

@luchsamapparat is attempting to deploy a commit to the authjs Team on Vercel.

A member of the Team first needs to authorize it.