next-auth 中 useSession、getSession 和 getServerSession 之间的区别?

in4*_*3sh 1 next.js next-auth

我正在查看这个问题的答案,但我仍然不清楚有什么区别。而现在,他们又增加了一种新的方法getServerSession()。请澄清有什么区别以及何时使用什么

You*_*mar 6

它们都返回session与当前用户相关的内容,但在不同的上下文中。useSession是一个 React hook,类似于,并且根据Hooks 规则useState只能在客户端组件主体的顶部调用:

"use client";

import { useSession } from "next-auth/react";

export default function Component() {
  // This cannot be called in a if statement block, or inside a helper fucntion (Rules of Hooks)
  const { data: session, status } = useSession();

  //...
}
Run Code Online (Sandbox Code Playgroud)

要在客户端组件中获取会话而不遵循Hooks 规则,有getSession

"use client";

import { getSession } from "next-auth/client"


export default function Component() {
  // I'm able to get the sesson without following the Rules Of Hooks
  async function myFunction() {
    const session = await getSession()
    /* ... */
  }

  //...
}
Run Code Online (Sandbox Code Playgroud)

最后,要获取会话服务器端(路由处理程序、React 服务器组件),您可以使用getServerSession

import { getServerSession } from "next-auth/next"
import { authOptions } from "pages/api/auth/[...nextauth]"

export default async function Page() {
  const session = await getServerSession(authOptions)
  return <pre>{JSON.stringify(session, null, 2)}</pre>
}
Run Code Online (Sandbox Code Playgroud)