14

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

1 Answer 1

27

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" });
        }
    })
1
  • 4
    NextAuth v4.10.3 is not injecting the session on signIn success so the router.push('/dashboard') will be with session=null. To fix that, do a window.location.replace('/dashboard') which will trigger a full refresh. Hopefully this will be fixed soon. More details here github.com/nextauthjs/next-auth/issues/1264 Aug 21, 2022 at 5:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.