为什么我不能从nextjs 13中的session.user,serverside中提取id

pinkon5k  于 2023-05-06  发布在  其他
关注(0)|答案(1)|浏览(142)

当一切都正确设置时,我似乎无法从我的session.user(next-auth)中获取id。下面是我的一些代码。
/API/getId/index.ts在下面的代码中,我试图通过getServerSession访问我的会话,实际上我完整地取回了我的会话。然而,当我尝试user.id在会话中访问www.example.com时,我得到以下错误
类型“{ name?:字符串|零|未定义;电子邮件?:字符串|零|未定义;图像?:字符串|零|undefined;}'。

import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "../../auth/[...nextauth]";
import Prisma from '../../../../libs/prismadb'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    try{
        const session = await getServerSession(req, res, authOptions)
        console.log(session?.user.id, '1')
        if(session?.user){
            // const admin = await Prisma.owner.findUnique({
            //     where: {
            //         id: session?.user?.id
            //     }
            // })
            console.log(session, '2')
        }
        res.status(200).json({session})
    }catch(err: any){
        throw new Error(err)
    }
}

但它确实存在于那种类型上

export interface DefaultSession {
  user?: {
    name?: string | null
    email?: string | null
    image?: string | null
    id?: string | null
  }
  expires: ISODateString
}

我试着重新启动我的typescript服务器,甚至重新启动vscode,但似乎都不起作用。甚至当我尝试console.log(session)时,我看到id确实存在于user对象中。请帮助,如果你知道什么是错的,因为这是一个大的项目,我的工作,我不能落后于它

7fyelxc5

7fyelxc51#

首先,您需要确保在Nextauth回调中包含了session.user.id。它应该看起来像这样:

callbacks: {
    session({ session, user }) {
      if (session.user) {
        session.user.id = user.id;
      }
      return session;
    },
  },

如果存在,则需要使用“模块扩充”将id添加到DefaultSession的类型中,如下所示:

// next-auth.d.ts

import { DefaultSession } from "next-auth";

declare module "next-auth" {
  interface Session {
    user?: {
      id: string;
    } & DefaultSession["user"];
  }
}

^获取默认会话并将其添加为id字符串。你也可以使用模块扩充来添加一些其他的字段,比如role。
更多信息:https://next-auth.js.org/getting-started/typescript#module-augmentation
如果仍然不起作用,请确保数据库模式中存在id
让我知道如果工作:)

相关问题