While working on my NestJS application, I encountered a validation error when making a request to the http://localhost:3000/users/authstatus endpoint. The error message displayed was:
{
"message": "Validation failed (numeric string is expected)",
"error": "Bad Request",
"statusCode": 400
}
Let me provide a brief overview of my setup:
- Data Transfer Object (DTO Class - CreatePostDto):
import { IsInt, IsNotEmpty, IsNumberString, IsOptional, IsString } from 'class-validator';
export class CreatePostDto {
@IsNotEmpty()
@IsString()
title: string;
@IsNotEmpty()
@IsString()
content: string;
@IsOptional()
@IsString()
mainImageUrl: string;
@IsInt()
userId: number;
@IsInt()
categoryId?: number; // Optional field
}
- Current User Guard::
import { ExecutionContext } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
export class CurrentUserGuard extends AuthGuard('jwt') {
handleRequest(err: any, user: any) {
if (user) return user;
return null;
}
}
- JWT Strategy::
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { Request } from 'express';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(@InjectRepository(User) private readonly userRepo: Repository<User>) {
super({
jwtFromRequest: ExtractJwt.fromExtractors([(request: Request) => {
return request?.cookies?.Authentication;
}]),
ignoreExpiration: false,
secretOrKey: 'secretKey', // Use your own secret key here
});
}
async validate(payload: any, req: Request) {
if (!payload) {
throw new UnauthorizedException('Invalid JWT payload');
}
const user = await this.userRepo.findOneBy({ username: payload.username });
if (!user) {
throw new UnauthorizedException();
}
req.user = user;
return req.user;
}
}
- Current User Decorator and Endpoint::
import { ExecutionContext, createParamDecorator } from "@nestjs/common";
export const CurrentUser = createParamDecorator(
(data: unknown, context: ExecutionContext) => {
const request = context.switchToHttp().getRequest();
return request.user;
}
);
@Get('auth-status')
@UseGuards(CurrentUserGuard)
@HttpCode(HttpStatus.OK)
authStatus(@CurrentUser() user: User) {
console.log('Authenticated User:', user);
return { status: !!user, user };
}
I am stuck with a validation error suggesting that a numeric string is expected. I am unsure about the cause of the issue within the code or how to resolve it.
Actions taken so far:
1. Verified the correctness of the DTO and decorator usage
2. Inspected the request payload for any anomalies
3. Confirmed that the JWT strategy is properly configured
If you can offer any assistance or advice on rectifying this validation error, it would be highly appreciated! Thank you!