As a beginner in Next.js I came across NextAuthJS. I wanted to use custom email and password authentication and thus I went with Credentials Provider and configured as below
import NextAuth from "next-auth";
import CredentialsProvider from `next-auth/providers/credentials`
import ConnectToDB from "../../../lib/db";
import auth from "../../../lib/auth";
export default NextAuth({
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
},
providers: [
CredentialsProvider({
async authorize(credentials) {
const client = await ConnectToDB();
const db = client.db();
const user = await db.collection("users").findOne({ email: credentials.email });
if (!user) {
client.close();
throw new Error("User not found");
}
const isValid = await auth.verifyPassword(credentials.password, user.password);
if (!isValid) {
client.close();
throw new Error("Invalid password");
}
client.close();
return { _id: user._id };
},
}),
],
});
And used the signIn
method from next-auth/client
to signin as below
import { signIn } from "next-auth/client";
const submitHandler = async (e) => {
e.preventDefault();
const email = emailRef.current.value;
const password = passwordRef.current.value;
const result = await signIn("credentials", { redirect: false, email, password });
}
I tried to debug this and found no solution to but and later I realised that some error is being logged in to browser console
This is the error I am receiving
[next-auth][error][client_fetch_error]
I think you already solved your problem since it's been a while you asked the question. if not i'm intending my answer for also those who has the same issue.
Your code looks almost exactly the same in my one project but mine is working fine.
Well, you need to define credemtials: {}
object in the CredentialsProvider({ ... })
like the official doc example https://next-auth.js.org/configuration/providers/credentials.
The client_fetch_error
error. I assume, you are getting this in production, i had this issue also. You need to add a environment variable:
and redeploy.
you should either return null
or return user
in the authorize
, not throw error