How to handle login failed error in NextAuth.js?

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

Leave a Comment