skip to Main Content

I have a login/signup app in NextJS. In the login page logic within my route.ts file I am submitting a few requests to a MongoDB database. I am checking to see if a doesnt exist then to send a NextReponse with a 400 error. Same thing if a PW is wrong then send a 400. However, whats happening is I am getting a 500 Internal Server Error each time I enter in a wrong user or wrong password. What am I doing wrong with my logic?

Here’s the code:

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 exist
    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 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 sucessful",
      success: true,
    });

    response.cookies.set("token", token, { httpOnly: true });

    return response;
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

2

Answers


  1. Chosen as BEST ANSWER
     if (!user) {
          NextResponse.json( //add a return !
            { message: "User does not exist" },
            { status: 400, statusText: "User does not exist" }
          );
        }
    

    I forgot to add the return. It should be return NextResponse.json(...)

    :)


  2. i think the problem is with

    console.log(user.password)

    because you log the users password, however you only check wether user != null after this, so if you user is null, you try to acces password from null, then an error will be thrown, triggering your catch block

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search