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

5f0d552i  于 2023-03-29  发布在  其他
关注(0)|答案(1)|浏览(184)

我正在使用:

nextJS: 13.1.6
    nextAuth 4.19.2

我使用的是新的app/目录,它仍处于Beta测试阶段。
我的问题是,我试图在页面中检索有关用户的信息,然后基于该信息执行逻辑。例如,使用userID,并从数据库中获取额外的信息(然后在服务器端预呈现页面)。
在[..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;
        }
      },

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

"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>
  </>
}

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

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>;    

}

返回如下数据(所有额外信息均缺失):

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

在我的[... nextauth].js authorize(credentials)脚本中,我返回了一个用户对象,看起来像这样:

{
  id: '123456',
  userName: 'myUserName',
  email: 'abc@myserver.com',
  fullname: 'John Smith Jr',
  name: 'John Smith Jr'
}

如何访问服务器端的userID等数据?

uqjltbpv

uqjltbpv1#

对不起,我昨天看到有人试着回答这个问题,但是他的答案今天早上就没有了。
我想跟进并回答这个问题,因为我知道答案.那个人的答案是正确的.
调用getServerSessions(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>;    

}

相关问题