19

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" });
      });
juliomalves
  • 42,130
  • 20
  • 150
  • 146
Yousuf
  • 241
  • 1
  • 2
  • 9

1 Answers1

36

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" });
        }
    })
juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 5
    `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 https://github.com/nextauthjs/next-auth/issues/1264 – Gabriel Linassi Aug 21 '22 at 05:39
  • @GabrielLinassi saved my day. This problem still exist in `v4.21.1`. `router.push` followed by `router.reload` did NOT solve the problem. `window.location.replace` does. – Henry Fung Jul 19 '23 at 03:31