Fixing validation error in NestJS when using forbidUnknwonValues

Photo by Sergi Kabrera on Unsplash

If you get unexplained validation errors (http status 400) when calling a NestJS api you might want to check your Query() parameters. Parsing and validating these the wrong way can cause issues.

Parsing Query parameters in NestJs

There are two ways to parse query strings in Nest Js. You can parse each variable separately or parse an object. Complex parameters cause issues when parsing from query strings. I would always recommend parsing via an object if you use any kind of non-string parameters.

e.g.

@Controller("myController")
export class MyControllerController {
  @Get()
  async myMethod(
    @Query("param1") param1?: string,
    @Query("param2", new ParseArrayPipe({ items: String, optional: true }))
    param2?: string[]
  ): Promise<void> {}
}

The param2 there will break forbidUnknownValues. Class validator can't parse it correctly.

Instead you can define an object that describes all the parameters. Define the required transforms and tell nest to run both validation and transformation on the query string to get the right values out.

Create a model that describes the parameters.

import { Type, Transform } from "class-transformer";
import {
  IsArray,
  IsDate,
  IsDefined,
  IsEnum,
  IsOptional,
} from "class-validator";

export default class QueryParams {
  @IsString()
  @IsOptional()
  public param1!: string;

  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  @Type(() => String)
  @Transform((value: string) => value.split(","))
  public param2?: string[];
}

and then change the controller to use this model instead of individual query string parameters.

@Controller("myController")
export class MyControllerController {
  @Get()
  async myMethod(
    @Query(new ValidationPipe({ transform: true })) allQueryParams: QueryParams
  ): Promise<void> {}
}

Conclusion

You should be able to use the forbidUnknownValues setting in the validation pipe configuration as expected now. In general once I have more than 2-3 query parameters in an api method I think it's easier to use a query object.