0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NextAuth.js (Auth.js) のBroadcast機構

Posted at

SessionProvider (v5はこちら) には、複数のタブでアプリケーションを表示している時に、タブ間でセッション状態を同期する仕組みがある。1つのタブでクライアントサイドからAPI呼び出しが発生したことをトリガに、他のタブにメッセージを送って (この機構はBroadcastと呼ばれる) 、クライアントサイドでのセッション取得 (GET /api/auth/session) を引き起こすことで実現されている。

ドキュメント上の記載

この機構についてはNextAuth.jsのドキュメントに細かく記載されていないが、該当するのはClient APIの下記の箇所となる。

Using the supplied <SessionProvider> allows instances of useSession() to share the session object across components, by using React Context under the hood. It also takes care of keeping the session updated and synced between tabs/windows.

Every tab/window maintains its own copy of the local session state; the session is not stored in shared storage like localStorage or sessionStorage. Any update in one tab/window triggers a message to other tabs/windows to update their own session state.

Broadcastが発生するタイミング

NextAuth.jsのv4とv5で、どの操作のタイミングでBroadcastが発生するかを調査した。

操作 v4 v5
サインイン 発生しない 発生しない
ページ表示 session注入あり 発生しない 発生しない
ページ表示 session注入なし 発生する (GET /auth/api/session) 発生する (GET /auth/api/session)
サインアウト 発生する (POST /auth/api/signout) 発生しない

※ 「session注入」はSessionProviderにSSRで取得したsessionオブジェクトを渡す実装のことを指す。

※ () 内はBroadcastのトリガとなる通信。

補足
  • v4では npm run dev (Strict Mode有効) で動かすと、session注入ありでもBroadcastが発生する。
  • v5ではセッション取得が複数回発生する。詳細は未確認だが、このIssueが関係しているようである。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?