在next-auth中,如何在服务器端获取userID(nextjs 13应用程序目录)

NL3*_*294 5 next.js next-auth

我在用着:

    nextJS: 13.1.6
    nextAuth 4.19.2
Run Code Online (Sandbox Code Playgroud)

我正在使用新的 app/ 目录,该目录仍处于测试阶段。

我的问题是我试图检索页面中有关用户的信息,然后根据该信息执行逻辑。例如,使用用户 ID,并从数据库中获取额外信息(然后在服务器端预渲染页面)。

在 [..nextauth.js] 中,我在 jwt 和会话回调中添加了额外的信息,如下所示:

      callbacks: {
        async jwt({token, user}) {
      
           if (user?.id) {
               token.id = user.id
           }
           if (user?.userName) {
               token.userName = user.userName;
           }

          if (user?.fullname) {
            token.fullname = user.fullname;
          }

                      
           return token
        },
        async session({session, token, user}) {
            session.userID = token.id;
            session.userName = token.userName;
            
            session.fullname = token.fullname;

            //I also tried it this way, according to the docs at:
            //  https://next-auth.js.org/configuration/callbacks
            session.user.userID = token.id;
            session.user.fullname = token.fullname;

            return session;
        }
      },      
Run Code Online (Sandbox Code Playgroud)

在客户端,我可以像这样检索用户名等数据:

"use client"; // this is a client component.

import { useSession, signIn, signOut } from "next-auth/react"

export default  function LoginPlaceholder() {
  const { data: session } = useSession();


  if(session) {

 console.log(session);
    return <>

      Welcome, {session.userName} 

      <button onClick={() => signOut()}>Sign out</button>
    </>
  }
  return <>
    <br/>
    Not signed in <br/>
    <button onClick={() => signIn()}>Sign in</button>
  </>
}
Run Code Online (Sandbox Code Playgroud)

但是,在服务器端,我无法检索附加信息。

export default async function EditUsernamePasswordPage(props) {
    const data = await getData();

    //this is how to get session data in the Next.js 13 apps folder
    //https://twitter.com/nextauthjs/status/1589719535363715072?lang=en
    const session = await getServerSession();
    console.log(session);

    return <pre>{JSON.stringify(session, null, 2)}</pre>;    

}
Run Code Online (Sandbox Code Playgroud)

返回这样的数据(缺少所有额外信息):

{
  user: {
    name: 'John Smith Jr',
    email: 'abc@myserver.com',
    image: undefined
  }
}

Run Code Online (Sandbox Code Playgroud)

在我的 [...nextauth].js 授权(凭据)脚本中,我返回一个如下所示的用户对象:

{
  id: '123456',
  userName: 'myUserName',
  email: 'abc@myserver.com',
  fullname: 'John Smith Jr',
  name: 'John Smith Jr'
}
Run Code Online (Sandbox Code Playgroud)

如何获取服务器端的用户ID等数据?

NL3*_*294 7

抱歉,我昨天看到有人试图回答这个问题,但今天早上他的答案消失了。

我想跟进并回答这个问题,因为我找到了解决方案。那个人的回答是正确的。

您需要调用 getServerSessions(authOptions); 与 authOptions. 如果不这样做,那么 getServerSessions() 将仅返回一些基本字段。

  import {authOptions} from "@/pages/api/auth/[...nextauth]"; 
export default async function EditUsernamePasswordPage(props) {
    const data = await getData();

    //this is how to get session data in the Next.js 13 apps folder
    //https://twitter.com/nextauthjs/status/1589719535363715072?lang=en
    const session = await getServerSession(authOptions);
    console.log(session);

    return <pre>{JSON.stringify(session, null, 2)}</pre>;    

}
Run Code Online (Sandbox Code Playgroud)