如何处理 NextAuth.js 中的登录失败错误?

You*_*suf 25 reactjs next.js next-auth

我使用 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" });
      });
Run Code Online (Sandbox Code Playgroud)

jul*_*ves 47

当传递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
}
Run Code Online (Sandbox Code Playgroud)

您必须处理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" });
        }
    })
Run Code Online (Sandbox Code Playgroud)

  • `NextAuth v4.10.3` 不会在登录成功时注入会话,因此 router.push('/dashboard') 将使用 `session=null`。要解决这个问题,请执行“window.location.replace('/dashboard')”,这将触发完全刷新。希望这个问题能尽快得到解决。更多详细信息请参见 https://github.com/nextauthjs/next-auth/issues/1264 (6认同)

归档时间:

查看次数:

31000 次

最近记录:

3 年,5 月 前