会话的用户 ID 不存在

问题描述 投票:0回答:1

我是 nextjs 世界的新手。我想实现下一个身份验证,到目前为止我已经通过凭据提供程序成功完成了,但是当使用 useSession() 时,用户只有姓名和电子邮件。

const handler = NextAuth({
  secret: process.env.NEXTAUTH_SECRET!,
  session: {
    strategy: "jwt",
  },

  providers: [
    CredentialsProvider({

      name: "Credentials",

      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        const user = await AuthService.getUserByEmail(credentials?.email!);

        return {
          id: user._id.toString(),
          email: user.email,
          name: user.name,
        };
      },
    }),
  ],
  callbacks: {
    async session({ session, token }) {
      session.user.id = token.sub;
      return session;
    },
  },
});

export { handler as GET, handler as POST };

//and page.tsx
"use client";
import { useSession } from "next-auth/react";


export default function Home() {
  const { data: session } = useSession();
  console.log(session);

next.js
1个回答
0
投票

这就是我在研究了你如何实现你的代码后最终能够使用它并修改我的代码的方式 这是文件路径 [app/api/auth/[...nextauth]/routes

import NextAuth, { getServerSession } from "next-auth";
import GoogleProvider from "next-auth/providers/google";

const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
  // secret: process.env.NEXTAUTH_SECRET,
  callbacks: {
    session: ({ session, token }) => ({
      ...session,
      user: {
        ...session.user,
        id: token.sub,
      },
    }),
  },
  //end of the callback
});

export { handler as GET, handler as POST };
© www.soinside.com 2019 - 2024. All rights reserved.