I am using next-auth.js version 4.19.2 with the "credentials" (db) provider and some custom sign-in, and signout pages. I seem unable to return what it expects from the authorize() handler. I would like to return the authenticated user or an error message. I tried ‘return user’ and ‘return null’ as well as resolving and rejecting a Promise ‘return Promise.resolve(user)’ and ‘return Promise.reject(null)’… neither worked. Can someone spot the issue below? Thank you!
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google";
import User from "../../../../models/User";
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
CredentialsProvider({
name: "Credentials",
async authorize(credentials, req) {
const { username, password } = credentials;
const user = await User.findOne({ email: username }).exec();
if (user) {
console.log("user", user);
await user.comparePassword(password, function (err, isMatch) {
console.log("comparePassword err, isMatch", err, isMatch);
if (err) throw err;
if (isMatch) {
console.log("IS MATCH!");
return Promise.resolve(user);
}
});
} else {
return Promise.reject(null);
}
},
}),
],
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: "/auth/signin",
signOut: "/auth/signout",
error: "/auth/error", // Error code passed in query string as ?error=
verifyRequest: "/auth/verify-request", // (used for check email message)
newUser: "/auth/new-user", // New users will be directed here on first sign in (leave the property out if not of interest)
},
};
export default NextAuth(authOptions);
Using it like this:
<button
type="submit"
className="btn btn-primary w-100 mt-4"
onClick={() =>
signIn("credentials", {
redirect: false,
username: state.username,
password: state.password,
callbackUrl: "/",
}).then(({ ok, error }) => {
if (ok) {
alert("OK");
} else {
console.log(error);
alert("NOT OK");
}
})
}
>
Sign in
</button>
What am I doing wrong here?
4
Answers
The issue was with the signin had a form tag that was getting submitted at the same time as the sign in ajax call.
You have to return an object not a promise :
Also here you are only returning the
user
you are not storing it in yoursession
to do that you should use callbacks :This my current next-auth with credentials and it working fine
Since you use this
await user.comparePassword
, you must definecomparePassword
onuserSchema
. It should be like thisif you set this correctly then in
authorize()