I am building a web app using nextjs and next-auth. On submit I call the next-auth signIn method, and make an post request to an endpoint.
The problem is the SigninResponse doesn’t return relevant error messages from my API, e.g. when the user is not verified. I need these to redirect the user based on any of the messages, is there a work around this. How do I updated SigninResponse to contain my responses, which I need. I’ve spent 2 days checking their docs. Please find below some code snippets.
authorize
authorize: async (credentials) => {
const payload = await LoginSchema.parseAsync(credentials)
console.log({ payload, credentials });
const response = await loginUser(payload);
const { status, user, message } = response as LoginResultProps;
if (status !== "success") {
if (message?.toLowerCase() === "email not verified") {
throw new Error(message as string ?? "Email not verified");
} else if (message?.toLowerCase() === "invalid login combination") {
throw new Error(message as string ?? "Invalid login combination");
} else {
throw new Error(message as string ?? "An error occurred trying to Log in");
}
}
if (!user || user === null) {
return null
} else {
return user
}
},
onSubmit
try {
await signIn("credentials", payload).then(res => {
if (!res?.error) {
form.reset();
toast({
variant: "success",
description: (
<ToastSuccess title="Log in successful" />
)
})
const user_type = session && session.data?.user.user_type as string;
setTimeout(() => {
if (user_type === "xx") router.push("/xx");
if (user_type === "yy") router.push("/yy");
if (user_type === "zz") router.push("/zz");
}, 1500);
} else {
setNotificationType({
type: "failed",
title: "Request failed",
description: res?.error?.message
});
setIsOpenNotification(true);
}
});
} catch (error) {
if (error instanceof AuthError) {
switch (error.type) {
case "CredentialsSignin":
return { error: "Invalid credentials" };
default:
return { error: "An error occurred" };
}
}
throw error;
}
Thanks.