Implementing User Authentication Through Credentials And MongoDB
Unanswered
German yellowjacket posted this in #help-forum
German yellowjacketOP
I am using "next-auth": "^5.0.0-beta.18",
Whenever I try to navigate to the root page while running it on localhost I get this error
This is my User Model
User.js
Whenever I try to navigate to the root page while running it on localhost I get this error
⨯ src\models\User.js (28:1) @ <unknown>
⨯ Cannot read properties of undefined (reading 'User')This is my User Model
User.js
import mongoose, { Schema, models } from "mongoose";
import { v4 as uuidv4 } from 'uuid';
const userSchema = new Schema(
{
userId: {
type: String,
unique: true,
default: uuidv4, // Use UUID v4 to generate a unique ID
},
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
},
{ timestamps: true }
);
const User = models.User || mongoose.model("User", userSchema);
export default User;1 Reply
German yellowjacketOP
auth.js
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import User from './models/User';
export const BASE_PATH = '/api/auth';
const authOptions = {
providers: [
Credentials({
name: 'Credentials',
credentials: {
username: { label: 'Username', type: 'text' },
password: { label: 'Password', type: 'password' }
},
async authorize(credentials) {
if (credentials === null) return null;
try {
// Find the user by email in the database
const user = await User.findOne({ email: credentials.username });
// Check if the user exists
if (!user) {
throw new Error('Invalid Email');
}
// Compare the password from the form with the password from the database
if (user.password !== credentials.password) {
throw new Error('Invalid Password');
}
return user;
}
catch (error) {
throw new Error('Invalid credentials');
}
},
}),
],
basePath: BASE_PATH,
secret: process.env.NEXTAUTH_SECRET,
};
export const { handlers, auth, signIn, signOut } = NextAuth(authOptions);