'Next Auth "Credentials" redirection when throwing error on custom login page
I have a custom login page, which in turn calls the signIn()
function when submitting the form.
I am only using the "Credentials" provider.
Server-side, I am just trying to throw an error so I can handle it on the frontend. Seems like something that would be easy.
I continue to get an error that states:Error: HTTP GET is not supported for /api/auth/login?callbackUrl=http://localhost:4000/login
The url I get redirected to is:http://localhost:4000/api/auth/login?callbackUrl=http://localhost:4000/login
Here is my code: pages/login.js (only relevant code. Rest is just layout.)
<form
method="post"
onSubmit={() =>
signIn("credentials", {
email: "test",
password: "test",
})
}
>
<label>
Username
<input type="email" />
</label>
<label>
Password
<input name="password" type="password" />
</label>
<button type="submit">Sign In</button>
</form>
pages/api/auth/[...nextauth.js]
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
const options = {
site: process.env.NEXTAUTH_URL,
providers: [
Providers.Credentials({
id: "chatter",
name: "Credentials",
type: "credentials",
credentials: {
email: { label: "Email", type: "email", placeholder: "[email protected]" },
password: { label: "Password", type: "password" },
},
authorize: async credentials => {
console.log("credentials:", credentials);
throw new Error("error message"); // Redirect to error page
},
}),
],
pages: {
signIn: "login",
newUser: null,
},
};
export default (req, res) => NextAuth(req, res, options);
Solution 1:[1]
You can use something like this:
signIn("credentials", {
redirect: false,
email: "test",
password: "test",
})
.then((error) => console.log(error))
.catch((error) => console.log(error));
Solution 2:[2]
Do you check [...nextauth].js in pages/api/auth?
I had same issue, but I can fix [...nextauth].js move 'pages/api' to 'pages/api/auth'.
Solution 3:[3]
This answer helped me solve my issue:
https://stackoverflow.com/a/70760933/11113465
If you set redirect
to false, the signIn
method will return a promise of 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
}
And then you can handle the error as you like:
const { error } = await signIn('credentials', {
phone_number: phoneNumber,
verification_code: code.toString(),
redirect: false,
});
if (error) {
// handle error
} else {
router.push(callbackUrl);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | sungmin yim |
Solution 3 | Ali Havasi |