I have developed a login/signup application using NextJS. When attempting to log in, the logic in my route.ts file sends requests to a MongoDB database to check if the user exists and if the password is correct. However, instead of receiving the expected 400 error response when entering wrong credentials, I am consistently getting a 500 Internal Server Error. What could be causing this issue with my current logic?
Here is the code snippet:
import { connect } from "@/dbConfig/dbConfig";
import User from "@/models/userModel";
import { NextRequest, NextResponse } from "next/server";
import bcryptjs from "bcryptjs";
import jwt from "jsonwebtoken";
connect();
export async function POST(request: NextRequest) {
try {
const reqBody = await request.json();
const { password, email } = reqBody;
console.log(reqBody);
// Check if user exists
const user = await User.findOne({ email });
console.log(user.password);
if (!user) {
NextResponse.json(
{ message: "User does not exist" },
{ status: 400, statusText: "User does not exist" }
);
}
// Check if password is correct
const validPassword = await bcryptjs.compare(password, user.password);
if (!validPassword) {
return NextResponse.json(
{},
{ status: 400, statusText: "Invalid Password" }
);
}
// Create token data
const tokenData = {
id: user._id,
username: user.username,
email: user.email,
};
// Create token
const token = await jwt.sign(tokenData, process.env.TOKEN_SECRET!, {
expiresIn: "1d",
});
const response = NextResponse.json({
message: "Login successful",
success: true,
});
response.cookies.set("token", token, { httpOnly: true });
return response;
} catch (error: any) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}