🐞프로그래밍/Next.js

[정보] NextAuth.js Type 에러 잡기 - CredentialsProvider / prisma

TwoIceFish 2024. 2. 7. 10:41

 

수정 포인트는 2개이다.

credentials의 type을 명시, 로그인 성공하고 return 되는 user 값을 any로 반환

 

 

import bcrypt from "bcrypt";
import NextAuth, { AuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

import prismadb from "@/app/lib/prisma";
import { PrismaAdapter } from "@auth/prisma-adapter";

export const authOptions: AuthOptions = {
  providers: [
    CredentialsProvider({
      name: "credentials",
      
      // 아래 credentials의 기본 포맷이 설정되어야한다.
      credentials: {
        email: {},
        password: {},
      },
      async authorize(credentials) {
        // User
        console.log(credentials);
        if (!credentials?.email || !credentials?.password) {
          throw new Error("ID&PW mismatch");
        }

        const user = await prismadb.user.findUnique({
          where: {
            email: credentials.email,
          },
        });
        if (!user) {
          throw new Error("Contact Admin");
        }

        const isCorrectPassword = await bcrypt.compare(
          credentials.password,
          user.hashedPassword,
        );

        if (!isCorrectPassword) {
          throw new Error("ID&PW mismatch");
        }
		
        // as any로 반환해야 오류가 안뜬다.
        return user as any;
      },
    }),
  ],
  session: {
    strategy: "jwt",
  },
  pages: {
    signIn: "/",
  },
  secret: process.env.NEXTAUTH_SECRET,
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };