I'm trying to create an auth app with the newest version of Auth, but in Credentials after all the logic get the user from database, when it will return to Session is coming null, I tried to force data to see if works but doesn't.
import bcrypt from "bcryptjs"
import type { NextAuthConfig } from "next-auth"
import Credentials from "next-auth/providers/credentials"
import { LoginSchema } from "@/utils/schemas/index"
import getUserByEmail, { } from "@/database/getUserByEmail"
export default {
providers: [
Credentials({
async authorize(credentials): Promise<any> {
const validatedFields = LoginSchema.safeParse(credentials)
if (validatedFields.success) {
const { email, password } = validatedFields.data
const user = await getUserByEmail(email)
if (!user || !user.Senha) return null
const passwordsMatch = await bcrypt.compare(
password,
user.Senha,
)
if (passwordsMatch) {
console.log(typeof user) // is a valid object
return user
}
}
return null
}
})
],
} satisfies NextAuthConfig
My auth.ts is here:
import NextAuth from "next-auth"
import authConfig from "./auth.config"
import { db } from "@/database/db"
import { PrismaAdapter } from "@auth/prisma-adapter"
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
adapter: PrismaAdapter(db),
session: { strategy: "jwt" },
...authConfig,
})
console.log(typeof user)
is not a good way to debug since console.log(tyepof null)
is "object"
. Try to run this code:
console.log(typeof null)
Try instead to log the user
object itself and see the real value:
console.log(user)
You have some cases where you return null
:
validatedFields.success === false
!user
!user.Senha
!passwordsMatch
Try to debug them one by one:
export default {
providers: [
Credentials({
async authorize(credentials): Promise<any> {
const validatedFields = LoginSchema.safeParse(credentials)
if (validatedFields.success) {
const { email, password } = validatedFields.data
const user = await getUserByEmail(email)
console.log({user, userSenha: user.Senha})
if (!user || !user.Senha) return null
const passwordsMatch = await bcrypt.compare(
password,
user.Senha,
)
if (passwordsMatch) {
console.log(user)
return user
} else {
console.log("Password didn't match")
return null
}
} else {
console.log("Credentials are not valid")
return null
}
// You can get rid of this return
return null
}
})
],
} satisfies NextAuthConfig
This way you can know where exactly the bug is
Additionally you can enbal NextAuth.debug
config to get more detailed insights about the authentication status in your app
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
debug: proccess.env.NODE_ENV === "development", // enable in dev - disable in production
adapter: PrismaAdapter(db),
session: { strategy: "jwt" },
...authConfig,
})