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

21

我正在使用NextAuth.js进行Next.js身份验证。登录功能正常,但是在错误的凭据上,页面仍在重新加载。它不显示任何错误。我需要处理错误以显示某种提示消息。

signIn("credentials", {
      ...values,
      redirect: false,
    })
      .then(async () => {
        await router.push("/dashboard");
      })
      .catch((e) => {
        toast("Credentials do not match!", { type: "error" });
      });
1个回答

42

当将{{link1:redirect: false}}传递给其选项时,signIn将返回一个Promise,该Promise{{link2:仅在电子邮件和凭据提供程序类型中}}解析为具有以下格式的对象。

{
    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" });
        }
    })

6
NextAuth v4.10.3 在登录成功后没有注入 session,因此 router.push('/dashboard') 将携带 session=null。为了解决这个问题,请执行 window.location.replace('/dashboard'),将会触发完整的刷新。希望这个问题很快就能得到解决。更多细节请参考 https://github.com/nextauthjs/next-auth/issues/1264。 - Gabriel Linassi
@GabrielLinassi救了我的一天。这个问题在v4.21.1版本中仍然存在。使用router.push后跟router.reload并不能解决这个问题,但是使用window.location.replace可以解决。 - Henry Fung
此问题已在v4.24.3版本中修复。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接