Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle login failed error in NextAuth.js?

I'm using NextAuth.js for Next.js authentication. Login works fine, but the page is still reloading on wrong credentials. It doesn't show any error. I need to handle error to show some kind of toast message.

signIn("credentials", {
      ...values,
      redirect: false,
    })
      .then(async () => {
        await router.push("/dashboard");
      })
      .catch((e) => {
        toast("Credentials do not match!", { type: "error" });
      });
like image 616
Md Yousuf Ali Avatar asked Sep 05 '25 20:09

Md Yousuf Ali


1 Answers

When passing redirect: false to its options, signIn will return a Promise that only in email and credentials provider types resolves to an object with the following format.

{
    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
}

You have to handle any errors inside the then block, as it won't throw an error.

signIn("credentials", { ...values, redirect: false })
    .then(({ ok, error }) => {
        if (ok) {
            router.push("/dashboard");
        } else {
            console.log(error)
            toast("Credentials do not match!", { type: "error" });
        }
    })
like image 200
juliomalves Avatar answered Sep 08 '25 12:09

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!