九、NextAuth 的 Client API

簡介

  • Session 對象:
{
  user: {
    name: string
    email: string
    image: string
  },
  expires: Date 
}
  • Session 數(shù)據(jù)對象并不包含敏感信息,比如Session-Token或者OAuth-Token,它只加載頁面顯示所需要的最小數(shù)據(jù),比如Name、Email、Image,如果需要自定義sessiion對象,需要使用 session callback
  • 需要確保 <SessionProvider> 添加到 pages/_app.js 中,并作為頂級元素。
  • 使用舉例:
import { useSession } from "next-auth/react"

export default function Component() {
  const { data: session, status } = useSession()

  if (status === "authenticated") {
    return <p>Signed in as {session.user.email}</p>
  }

  return <a href="/api/auth/signin">Sign in</a>
}

useSession()

  • 注意,這個函數(shù)客戶端可用,但是服務端是不可用的。

  • useSession() returns an object containing two values: data and status:

  • data 的取值可能是 undefinednull.

    • 當session不存在時 data 返回 undefined
    • 當session檢索失敗時, data 返回 null
    • 在成功的情況下 data 返回 Session.
  • status: 是一個枚舉,取值包括 "loading" | "authenticated" | "unauthenticated"

onUnauthenticated() 回調(diào)

  • 通常情況下,可以再 useSession 中加入 onUnauthenticated() 回調(diào)來處理沒有授權的情況,舉例:
import { useSession } from "next-auth/react"

export default function Admin() {
  const { status } = useSession({
    required: true,
    onUnauthenticated() {
      // The user is not authenticated, handle it here.
    },
  })

  if (status === "loading") {
    return "Loading or not authenticated..."
  }

  return "User is logged in"
}

結束

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容