Encountering a TypeScript error that states:
"Argument of type 'string | undefined' is not assignable to parameter of type 'string | Buffer'."
An attempt to integrate NextAuth into a Next.js 14 application and configure login credentials for comparing passwords during login. However, the specific error arises when handling the input password in the following line:
const passwordOk =
existingUser && bcrypt.compareSync(password, existingUser.password)
Here is the complete options file:
import CredentialsProvider from "next-auth/providers/credentials"
import type { NextAuthOptions } from "next-auth"
import connectMongoDB from "@/lib/mongodb"
import bcrypt from "bcrypt"
import User from "@/models/user"
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: {},
password: {},
},
async authorize(credentials, req) {
const email = credentials?.email
const password = credentials?.password
await connectMongoDB()
const existingUser = await User.findOne({ email })
const passwordOk =
existingUser && bcrypt.compareSync(password, existingUser.password)
if (passwordOk) {
return existingUser
} else {
return null
}
},
}),
],
}
Attempts were made to manually assign a type to the password but were unsuccessful:
const password: string | Buffer = credentials?.password
Another attempt was made:
const passwordOk =
existingUser &&
password &&
bcrypt.compareSync(password, existingUser.password)
The error disappeared, although unsure if this is considered best practice.