Skip to main content
NestJS ValidationPipe in Production: How We Use whitelist, Nested DTOs and Explicit Transforms to Stop Bad Input

NestJS ValidationPipe in Production: How We Use whitelist, Nested DTOs and Explicit Transforms to Stop Bad Input

December 3, 2026
Backend Engineering
9 min read

NestJS's ValidationPipe checks only the properties that carry class-validator decorators, so its defaults let unknown fields, unvalidated nested objects and mis-converted query strings reach your services. We register it once as an APP_PIPE provider with whitelist, forbidNonWhitelisted and explicit per-field transforms, and we keep enableImplicitConversion off because it turns ?active=false into true.

Every NestJS API our team builds validates input with ValidationPipe, the built-in NestJS pipe that turns a request payload into a DTO class instance with class-transformer and then checks it against class-validator decorators. It looks like a one-line setup. In practice, most validation bugs we trace were requests the pipe accepted because its configuration told it to. These are the settings our team now starts every project with, and the specific inputs that slip through without it.

Key takeaways

Strip or reject unknown fields: whitelist: true removes properties that have no class-validator decorator, and forbidNonWhitelisted: true turns them into a 400 error, which blocks mass assignment.

Nested DTOs need two decorators: a nested property needs both @ValidateNested() and @Type(() => ChildDto), or the child DTO's rules never run.

Implicit conversion breaks booleans: with enableImplicitConversion: true, class-transformer turns the query string "false" into true for a boolean field, so explicit @Type() and @Transform() per field are safer.

@IsOptional() also skips null: a PATCH body of {"displayName": null} passes validation unless the field uses @ValidateIf((_, v) => v !== undefined).

Register the pipe as APP_PIPE: app.useGlobalPipes() in main.ts does not run in e2e tests that compile AppModule, so those tests validate nothing.

What does NestJS ValidationPipe actually check?

NestJS ValidationPipe checks only the DTO properties that have class-validator decorators; TypeScript types are erased at runtime, so an undecorated property is invisible to it. The pipe runs in two steps: class-transformer's plainToInstance() builds an instance of the DTO class from the JSON body, then class-validator's validate() runs the decorators on that instance.

With the default options, a body of {"email": "a@b.co", "role": "admin"} sent to a DTO that declares only email passes validation and reaches the controller with role still attached. This is the baseline we register in every NestJS app:

Our baseline registers ValidationPipe in AppModule under the APP_PIPE token from @nestjs/core, with whitelist: true, forbidNonWhitelisted: true, transform: true, and transformOptions set to enableImplicitConversion: false.

We register the pipe through the APP_PIPE token instead of app.useGlobalPipes() in main.ts because of e2e tests. A test that builds the app with Test.createTestingModule({ imports: [AppModule] }) never executes main.ts, so a pipe registered there is missing from every e2e test. The failure is quiet: a test that sends an extra field gets a 201 instead of a 400, and a suite that only checks happy paths never notices. The NestJS docs also note that useGlobalPipes() does not set up pipes for gateways and microservices in hybrid apps.

How do I stop mass assignment in NestJS?

Mass assignment in NestJS is stopped by whitelist: true plus forbidNonWhitelisted: true on ValidationPipe, together with DTOs that never declare fields the caller should not set. Mass assignment is an attack where the client adds a field the API never meant to accept, such as role, tenantId or emailVerified, and the server writes it because the DTO goes straight to the ORM, as in this.usersRepo.update(id, dto).

With forbidNonWhitelisted, that request fails with a 400 and the message property role should not exist. We prefer rejecting to stripping, because silent stripping also hides client bugs: a frontend that sends displayname instead of displayName never learns the field was ignored.

The whitelist has one surprise. It is built from decorators, not from TypeScript properties, so a DTO field that is declared but undecorated is stripped too. Every field gets at least one decorator, and a field that is deliberately unvalidated gets @Allow().

Derived DTOs are the other leak. If an admin CreateUserDto includes role, an UpdateProfileDto built with PartialType(CreateUserDto) includes it too. We derive user-facing DTOs with OmitType or PickType from @nestjs/mapped-types, or the same helpers from @nestjs/swagger when the API publishes OpenAPI:

In code, that is a class UpdateProfileDto that extends PartialType(OmitType(CreateUserDto, ['role', 'tenantId'])), so the user-facing PATCH DTO cannot carry either field.

Why are my nested DTOs not being validated?

Nested DTOs in NestJS are validated only when the property has both @ValidateNested() and @Type(() => ChildDto), because class-validator validates nested class instances and class-transformer creates those instances only when @Type() names the class. Without @Type(), the nested value stays a plain object with no decorator metadata.

What happens next depends on the class-validator version. Since class-validator 0.14, forbidUnknownValues defaults to true, and a plain nested object fails with the confusing message an unknown value was passed to the validate function. Where that option is turned off, the nested object passes silently and whitelist never looks inside it, so a smuggled items[0].unitPrice survives one level down. Either way, the rules written on the child DTO are not the rules running.

The fix is a CreateOrderDto whose items property carries @IsArray(), @ArrayMaxSize(100), @ValidateNested({ each: true }) and @Type(() => LineItemDto), where LineItemDto validates sku with @IsString() and quantity with @IsInt() and @Min(1).

@ArrayMaxSize(100) caps how much work one request can make the validator do.

Why does ?active=false become true in NestJS?

The query string ?active=false becomes true when ValidationPipe runs with transformOptions: { enableImplicitConversion: true }, because class-transformer converts each value to the property's reflected TypeScript type and converts to boolean with Boolean(value), which is true for every non-empty string. Query and route parameters always arrive as strings, so implicit conversion is tempting: page: number just works. The same option quietly inverts every boolean filter.

We keep implicit conversion off and convert each query field explicitly:

Our ListUsersQuery DTO converts page and limit with @Type(() => Number) before @IsInt(), @Min() and @Max(); converts active with a @Transform() that maps only the strings "true" and "false" and leaves anything else for @IsBoolean() to reject; and wraps a single tag value in an array so @IsString({ each: true }) always sees string[]. The transform reads the raw value from obj[key], the original plain object, so no earlier conversion can hide what the client sent.

The tag transform covers a second query-string trap: with the Express query parser, ?tag=a arrives as the string "a" and ?tag=a&tag=b arrives as an array, so the DTO normalizes both shapes to string[]. Single route parameters need the same care. With transform: true, ValidationPipe converts @Param('id') id: number with a plain numeric cast, so /users/abc yields NaN instead of a 400. We put ParseIntPipe or ParseUUIDPipe on those.

Why does @IsOptional() let null through on a PATCH?

@IsOptional() lets null through because it skips every other validator on the property when the value is null or undefined, not only when the key is missing. A PATCH body of {"displayName": null} therefore passes validation and reaches the database. Against a NOT NULL column that becomes a 500 instead of a 400; against a nullable column, the user clears a field the UI never offered to clear.

PartialType() applies @IsOptional() to every inherited property, so PATCH DTOs built from it inherit the same behavior. For fields where absent means "leave unchanged" and null is not a legal value, we declare them directly on the PATCH DTO instead of inheriting them:

The pattern is @ValidateIf((_, value) => value !== undefined) followed by @IsString() and @MaxLength(80): an absent key skips validation, and a key that is present, including null, must be a valid string.

Should I use class-validator or Zod for NestJS validation?

class-validator is the better fit for an existing NestJS codebase, because ValidationPipe, mapped types and @nestjs/swagger are built around decorated DTO classes. Zod is the better fit when the same schema must run in a Next.js frontend and a NestJS backend. Zod is a TypeScript-first schema library whose schemas both validate data and produce types through z.infer. The traps differ more than the feature lists suggest:

Unknown keys: class-validator keeps them unless whitelist is on; Zod's z.object() strips them and z.strictObject() rejects them.

Nested objects: class-validator needs @ValidateNested() and @Type(); Zod validates them through schema composition with no extra step.

Query-string booleans: enableImplicitConversion turns "false" into true; Zod's z.coerce.boolean() has the same trap, while z.stringbool() in Zod 4 parses "false" correctly.

Null on optional fields: class-validator's @IsOptional() accepts null; Zod's .optional() rejects null unless .nullable() is added.

OpenAPI: class-validator DTOs work natively with @nestjs/swagger; Zod needs an adapter such as nestjs-zod.

Sharing with a Next.js frontend: DTO classes pull class-validator and decorators into the client bundle; Zod schemas import cleanly as plain objects.

We do not mix the two inside one module. A codebase where half the DTOs strip unknown keys by default and half keep them is how mass assignment comes back.

FAQ

Q: What is the difference between whitelist and forbidNonWhitelisted in NestJS?

A: whitelist: true silently removes properties without class-validator decorators from the validated object. forbidNonWhitelisted: true, which only works together with whitelist, rejects the request with a 400 that names each unexpected property.

Q: Does ValidationPipe validate query parameters and route parameters?

A: Yes, when the parameter is typed as a DTO class, such as @Query() query: ListUsersQuery. Single primitive parameters like @Param('id') id: number are only converted, not validated, so we add ParseIntPipe or ParseUUIDPipe to them.

Q: Is enableImplicitConversion ever safe to use?

A: enableImplicitConversion is safe for DTOs that contain only number and string fields, but one boolean field turns "false" into true. Explicit @Type(() => Number) and @Transform() per field cost a few lines and keep each conversion visible in the DTO.

Q: Why does my NestJS e2e test accept invalid bodies that production rejects?

A: The ValidationPipe is probably registered with app.useGlobalPipes() in main.ts, which e2e tests built with Test.createTestingModule() never execute. Registering the pipe with the APP_PIPE provider in AppModule makes tests and production share it.