본문 바로가기
FrontEnd/Next.js

Credetials callback function handle error (next-auth v5)

by 위그든씨 2024. 6. 17.

https://github.com/nextauthjs/next-auth/pull/9871

 

feat: customizable `authorize()` error by balazsorban44 · Pull Request #9871 · nextauthjs/next-auth

This introduces a way to throw custom errors in the authorize() callback of the Credentials provider. Any generic or sensitive server error will continue to return error=Configuration (full error i...

github.com

기존 callback에서는 throw new Error로 처리했지만 CredentialSignin 을 활용하여 Custorm된 Error을 만들어줘야함

import NextAuth, { CredentialsSignin} from 'next-auth';

class CustomError extends CredentialsSignin {
    code = 'custom';
}
export const { handlers, auth, signIn, signOut } = NextAuth({
	//...
    providers:[
        Credentials({
        	authorize: async ({ email, password }) => {
                if (!email || !password)
                    throw new CustomError(
                        'Please enter your email and password'
                    );
                const user = await db.user.findFirst({
                    where: {
                        email,
                    },
                });
                if (!user) throw new CustomError('User not found');
                const isValid = verifyPassword(
                    password as string,
                    user.password!
                );
                if (!isValid) throw new CustomError('Invalid password');

                return user;
            },
        
        })

    ]

})