Numeric String Expected Error Encountered in NestJS DTO Validation

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:

  1. 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
}
  1. 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;
  }
}

  1. 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;
  }
}

  1. 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!

Answer №1

Take a moment to review your request and ensure that it is sending the userId as a string.

Keep in mind that the Class Validator will not automatically convert it for you, so inputting "1" will not work.

You have the option to apply a transform decorator that will handle the parsing to a string:

@Transform(({ value }) => value ? Number(value) : value)
@IsInt()
userId: number

Remember that the transform should precede the @IsInt() decorator.

Hope this information proves useful.

Additionally, you may consider utilizing the @IsNumberString() decorator as an alternative to @IsInt().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: Unable to find solutions for all parameters in (?, ?)

Below is the unit test I've written for my Angular 10 component, which showcases a tree view with interactive features: import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/for ...

Is there a way to ensure that the return type of a generic function is always optional in Typescript?

Is there a way to ensure the return type is always optional from a generic return type in functions? I specifically need the return types (data & error) to be optional at all times since one of them will always be undefined. TypeScript declarations i ...

Adjust the column count in mat-grid-list upon the initial loading of the component

My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until ...

Issue: The variable 'HelloWorld' has been declared but not utilized

Why am I encountering an error when using TypeScript, Composition API, and Pug templating together in Vue 3? How do I resolve this issue when importing a component with the Composition API and using it in a Pug template? ...

Angular 2 offers a powerful feature called ngFor that allows developers to

Is there a way to allow users to enter keywords in an input field to filter items within a list of menu items dynamically without using ngModel? I need this to be done without the use of buttons as well. Any suggestions for a workaround? <div class=" ...

Mastering the art of accessing properties in typescript post implementing Object.defineProperty

I was experimenting with the TypeScript playground trying to figure out decorators and encountered some questions. class PathInfo { functionName: string; httpPath: string; httpMethod: string; constructor(functionName: string, httpPath: str ...

The variable 'user' is being accessed before being properly initialized - in Angular

I've been doing some research on Google and StackOverflow to try and troubleshoot this error, but I'm still having trouble getting it fixed. Can anyone provide assistance? Below is the content of my auth-service.ts file: import { Injectable } fr ...

Steer clear of confirming form dropdowns in CodeIgniter

I've implemented a search function as shown below: public static function search_form() { $form = new Form('search_form'); $form->field('keyword', 'text', array ( 'min_length' => ...

Transform the dynamic JSON format into a key-value pair structure with nested children nodes

Looking to convert a dynamic JSON structure into a tree node: { "video": { "width": 1920, "height": 1080, "video_codec": "H264", "CBR": "4337025", "frame_rate& ...

Unlock the key to connecting the output of one observable to another in rxjs

I have a procedure for saving users in the database. These are the steps I take: 1) First, I validate the request. 2) Next, I hash the password. 3) Finally, I store the user details in the users collection along with the hashed password. Below is the ...

"Encountering a 'Module Not Found' error in Node.js after

Recently, I added a node-module to my project using the command: npm install typescript --save-dev However, when I tried running: tsc Windows displayed an error message indicating that "tsc" is an unknown command. Strangely, this issue does not occur o ...

The specified property ID is not found in the User type

I recently started using TypeScript and decided to practice by implementing user authentication with Passport.js in a small application. Challenge The issue I'm facing is related to instructing Passport.js to store the id property of the user in the ...

Issue: The use of destructuring props is required by eslint, and I'm currently working with a combination of react and types

I typically work with React in JavaScript, and I recently encountered an error message stating "Must use destructuring props at line 14" while trying to define a button for use in a form. Here is the code snippet in question: import React from 'react& ...

Does anyone know how to retrieve the application version or import the package.json file? Can't seem to find the solution on

I need to display the version from the package.json file in my Angular application. To import it, I allowed importing json by adding a few extra lines in tsconfig.json: { "compilerOptions": { "module": "commonjs", ...

Access the global window variable from index.html within a Vue component

In my Vue project, I am incorporating an Stencil.js component in the following manner: index.html: <script type="module" src="https://xxxxxx.s3-eu-west-1.amazonaws.com/topbar.esm.js"> </script> <script> window.addEventLis ...

When utilizing create-next-app, an error may occur stating that the produced JSX.Element cannot be assigned to a variable

After creating a new project with TypeScript using create-next-app, I encountered an error in the default homepage when opened in my IDE (WebStorm). The error message reads: "Initializer type () => JSX.Element is not assignable to variable type NextPa ...

Maintaining database consistency for multiple clients making simultaneous requests in Postgres with Typeorm and Express

My backend app is being built using Express, Typescript, Typeorm, and Postgres. Let's consider a table named Restaurant with columns: restaurant_id order (Integer) quota (Integer) The aim is to set an upper limit on the number of orders a restaura ...

What advantages do interfaces as data types offer in Angular compared to using classes?

After watching a tutorial from my teacher, he showed us this code snippet: https://i.sstatic.net/MA3Z9.png He mentioned that the products array, defined as type any [], is not taking advantage of TypeScript's strongly typing. He suggested using an I ...

Guide for transferring data from HTML to controller in Angular 4

Hello everyone, I am new to Angular and currently working on displaying a table based on the value of a toggle button. I have implemented a toggle button using Angular material, but I'm struggling to pass the data to my controller. I would really app ...

The Azure function application's automatic reload feature does not function properly with the v4 model

Struggling to get Azure Function to recognize and incorporate changes in source code. I have set up a launch task to initiate the local server and run an npm script with tsc -w in watch mode. While I can see the modifications reflected in the /dist folder ...