Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS returns 201 OK status even though in the response I get unauthorized error message

I am using NestJS as a backend framework and when doing Login service it is not returning a valid HTTP code. I used GlobalPipes on the app as it will be shown in the code provided. Also, the part of the code that is sending the error message is being activated and it sends the error message I put there but still the response has a bad code.

This is login code

async login(dto: LoginDto) {
    try {
      const user = await this.prisma.user.findUnique({
        where: {
          email: dto.email,
        },
      });

      if (!user) throw new ForbiddenException('Credentials incorrect');

      const pwMatches = await argon.verify(user.password, dto.password);

      if (!pwMatches) throw new ForbiddenException('Credentials incorrect');
      return this.signToken(user.id, user.email);
    } catch (error) {
      return error;
    }
  }
like image 335
Brimstone Avatar asked Jan 21 '26 14:01

Brimstone


1 Answers

I encountered a similar issue, stumbled upon your question, and realized what might be happening. The problem lies in your return of an error object, which leads NestJS to serialize it and return an HTTP status of 201 for POST requests.

When an exception is raised, whether by your code or more likely by the ORM, you will immediately enter the catch block. To address this, you should throw an exception within the catch block to properly propagate the ForbiddenException to the controller, rather than returning the error object.

async login(dto: LoginDto) {
try {
  const user = await this.prisma.user.findUnique({
    where: {
      email: dto.email,
    },
  });

  if (!user) return new ForbiddenException('Credentials incorrect');

  const pwMatches = await argon.verify(user.password, dto.password);

  if (!pwMatches) return new ForbiddenException('Credentials incorrect');
  return this.signToken(user.id, user.email);
} catch (error) {
 // put some logs here
 // some error handling
throw InternalServerException(`Something went wrong: ${error}`)
}

}

like image 66
Yosleivys Baez Acosta Avatar answered Jan 24 '26 02:01

Yosleivys Baez Acosta