Open zacharyblasczyk opened 1 month ago
Hi there, What I understand by your issue is that you want to throw some error when the authentication fails. We had a long discussion with a solution here https://github.com/nextauthjs/next-auth/issues/11747#issuecomment-2367785095 Check this out I have given a full example with images and two different ways to get the error on the client. If still you have issues you can ask. Peace
In your auth.js file you have to extend the error class like this
import NextAuth, { CredentialsSignin } from "next-auth"
import Credentials from "next-auth/providers/credentials"
class InvalidLoginError extends CredentialsSignin {
code = "Invalid identifier or password"
}
export const { handlers, auth } = NextAuth({
providers: [
Credentials({
credentials: {
username: { label: "Username" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
throw new InvalidLoginError()
},
}),
],
})
You can do this in a server action or so and it will throw the error Also note that if you have to handle separately when using the server signIn() and client signIn() from next-auth/react
Another breaking change is that the signIn method results is something like follow:
type SignInResult = {
ok: true;
status: 200;
error: string | null;
code: number | null;
url: string | null;
}
ok
is always true
and status
is always 200
.so if you were previously checking for result?.ok
you need to change that to !result?.error
in your login form on client side.
@ARiyou2000, Thank you for the update. I will take a look and try to update what we are doing here.
Provider type
Credentials
Environment
Reproduction URL
https://github.com/ctrlplanedev/ctrlplane
Describe the issue
In the documentation it states
Using the credentials provider to sign in causes the page to refresh and an invalid login doesn't allow me to catch and handle any built in errors if it is returning
null
.Form/hook use
Backend Logic
Provider Logic
How to reproduce
Create a from that uses
signIn
and acredentials
provider that returns null when a credential isn't found. Triggering that submit hook will cause the page to refresh instead ofsignIn
throwing an error that can gracefully be handled.Expected behavior
I expected the
signIn
to throw an error if it receives anull
response from the provider. It isn't possible to log in if the credential isnull
and while I can work around this by changing the logic to the following, it leaves more room for someone to accidentally leak if a user exists, and forces errors to be thrown and caught that don't create a lot of value.