UPDATE
It works now. All I had to change is
session: {
jwt: true,
strategy: "jwt"
}
I am new in next-auth. I was practicing next-auth sign-in with credentials using MongoDB as a database. Whenever I sign in with credentials, useSession doesn't return data as expected but if sign in with other providers like google and GitHub it returns data as expected. Below I have given my code.
[...nextauth.js] code:-
export default NextAuth({
// Configure one or more authentication providers
adapter: MongoDBAdapter(clientPromise),
session: {
jwt: true,
},
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
CredentialsProvider({
async authorize(credentials) {
const client = await connect();
const usersCollection = client.db().collection("users");
const user = await usersCollection.findOne({
email: credentials.email,
});
if (!user) {
client.close();
throw new Error("No user found!");
}
const isValid = bcrypt.compare(credentials.password, user.password);
if (!isValid) {
client.close();
throw new Error("Invalid password/email");
}
client.close();
return user;
},
}),
// ...add more providers here
],
callbacks: {
async session({ session, user, token }) {
session.user = token.user;
console.log(user)
return session
},
async jwt({ token, user }) {
if (user) {
token.user = user;
}
// console.log(token)
return token
},
},
});
signIn logic:
const handleSubmit = async (e) => {
e.preventDefault();
const status = await signIn("credentials", {
redirect: false,
email: emailRef.current.value,
password: passwordRef.current.value,
});
console.log(status); // {error: null, status: 200, ok: true, url: 'http://localhost:3000/login'}
console.log(session); // {data: null, status: 'unauthenticated'}
};
Sorry for my bad English. Thanks in advance. :)