我使用 NextAuth.js 进行 Next.js 身份验证。登录工作正常,但页面仍然以错误的凭据重新加载。它没有显示任何错误。我需要处理错误以显示某种 toast 消息。
signIn("credentials", {
...values,
redirect: false,
})
.then(async () => {
await router.push("/dashboard");
})
.catch((e) => {
toast("Credentials do not match!", { type: "error" });
});
redirect: false
传递给其选项时,signIn
将返回 Promise
,该 仅在电子邮件和凭据提供程序类型中 解析为具有以下格式的对象。
{
error: string | undefined // Error code based on the type of error
status: number // HTTP status code
ok: boolean // `true` if the signin was successful
url: string | null // `null` if there was an error, otherwise URL to redirected to
}
您必须处理
then
块内的任何错误,因为它不会抛出错误。
signIn("credentials", { ...values, redirect: false })
.then(({ ok, error }) => {
if (ok) {
router.push("/dashboard");
} else {
console.log(error)
toast("Credentials do not match!", { type: "error" });
}
})
我在使用
credentials
时使用了next-auth错误处理的方法
const res = await signIn("credentials", {
email: values.email,
password: values.password,
redirect: false,
});
if (res?.ok) {
console.log("res: ", res);
signIn("credentials", {
email: values.email,
password: values.password,
});
} else {
console.log("res: ", res);
// TODO: Show error message with toast
}
如果您使用
next-auth
、 credentials
和 sonner
,可以使用一些解决方法
const onSubmit = async (values: LoginSchemaType) => {
setIsFormLoading(true);
toast.promise(
async () =>
await signIn("log-in", {
email: values.email,
password: values.password,
redirect: false,
}).then((res) => {
if (res?.ok) {
return true;
} else if (res?.error) {
throw new Error(res.error);
}
}),
{
loading: "Authorizing...",
success: (data) => {
if (data) {
form.reset();
router.refresh();
return `Welcome`;
}
},
error: (err) => {
return err;
},
finally: () => {
setIsFormLoading(false);
},
}
);
};
对于
credentials
const loginProvider = Credentials({
id: "log-in",
credentials: {
email: {},
password: {},
},
authorize: async (credentials) => {
if (!credentials?.email || !credentials.password) {
throw new Error("Credentials not found");
}
try {
const { email, password } = await loginSchema.parseAsync(credentials);
const dbUser = await db.user.findFirst({
where: {
email: email,
},
});
if (!dbUser) {
throw new Error("User not found");
} else {
if (!dbUser?.password) {
throw new Error("No password is associated with this account");
}
const isMatch = await bcrypt.compare(password, dbUser.password);
if (!isMatch) {
throw new Error("Credentials are not correct");
}
}
return exclude(dbUser, ["password"]);
} catch (error: any) {
throw new Error(error?.message ?? "Oops, something went wrong!");
}
},
});