How does NestJS ValidationPipe work with class-validator?
ValidationPipe is a pipe that runs before your handler and decides from the parameter's declared type what to validate. Nest does not inspect your TypeScript at runtime. It reads the design:paramtypes metadata that the TypeScript compiler emits for decorated methods. That metadata gives the pipe a metatype, the DTO class. The pipe passes the plain JSON payload and that class to class-transformer's plainToInstance, then runs class-validator's validate against the resulting instance. Each decorator such as @IsEmail() or @Min(1) is stored as metadata on the class and becomes a rule here. Any failure produces a 400 with the collected constraint messages.
Three options control what reaches your handler:
whiteliststrips any property that has no validation decorator on the DTO.forbidNonWhitelistedrejects the request with a 400 instead of stripping the unknown property silently.transformpasses the class instance to the handler rather than the original plain object. It also converts primitive parameters, so a route param typednumberarrives as a number. Coercing fields inside a DTO by their TypeScript types requiresenableImplicitConversionintransformOptions.
The whole mechanism depends on experimentalDecorators and emitDecoratorMetadata. Some toolchains strip types without emitting that metadata. esbuild-based runners do this, for example. In that case the pipe receives no metatype, or receives Object, and treats the argument as something it should not validate. It returns the payload untouched and raises no error. Unit and e2e tests can then pass while running zero rules.
// Requires tsconfig: "experimentalDecorators": true, "emitDecoratorMetadata": true
import 'reflect-metadata';
import { Body, Controller, Post, ValidationPipe } from '@nestjs/common';
import { IsEmail, IsInt, Min } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email!: string;
@IsInt()
@Min(1)
age!: number;
}
@Controller('users')
export class UsersController {
@Post()
create(@Body() dto: CreateUserDto) {
return dto; // a CreateUserDto instance because transform: true
}
}
// Register in main.ts with app.useGlobalPipes(validationPipe)
export const validationPipe = new ValidationPipe({
whitelist: true, // strip properties without decorators
forbidNonWhitelisted: true, // ...or reject them with a 400 instead
transform: true, // hand the handler a class instance
transformOptions: { enableImplicitConversion: true }, // "30" -> 30 by TS type
});
// Guard for test runners: if the toolchain did not emit design:paramtypes,
// the pipe gets no metatype and skips validation without raising an error.
const paramTypes = Reflect.getMetadata('design:paramtypes', UsersController.prototype, 'create');
if (paramTypes?.[0] !== CreateUserDto) {
throw new Error('design:paramtypes missing: ValidationPipe will run no rules');
}
A class-validator DTO, a ValidationPipe configured with whitelist, forbidNonWhitelisted and transform, and a startup check that fails when the build tool did not emit the decorator metadata the pipe needs to find the DTO.
Why do DTO types and runtime rules drift apart with class-validator?
That is the extreme case, but drift also happens when validation does run. In class-validator, the TypeScript type annotation and the decorators are two separate declarations that the compiler never compares. You can declare age: string and decorate it with @IsInt(), and the build succeeds. At runtime, a request with a string age is rejected and a numeric age passes, while every consumer of the DTO treats the field as a string. Mark a property @IsOptional() but leave its type non-optional, and downstream code skips the undefined check the runtime now permits. Reviewers have to read both the decorators and the annotation, and the tooling can't flag a mismatch between them.
Nested objects add a second layer. @ValidateNested() only validates a value that is an instance of a decorated class. A JSON body contains plain objects, so class-transformer must instantiate the nested property, and it only does that when the property also carries @Type(() => AddressDto). If you leave out @Type, the nested rules never apply. Depending on your class-validator version and the forbidUnknownValues setting, the payload either passes unchecked or fails with a generic unknown-value error that doesn't name the field. Arrays of nested DTOs also need each: true. None of this shows up at compile time.
The cause is structural. With class-validator, the class owns the static type and the decorators own the runtime contract, and you keep the two in sync by hand. Which library fits depends on where you want the single source of truth for your types to live.
import { IsInt, IsOptional, IsString, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
class AddressDto {
@IsString()
city: string;
}
class ItemDto {
@IsString()
sku: string;
}
export class CreateUserDto {
// Compiles fine: the annotation says string, the decorator demands an integer.
// At runtime, "42" is rejected and 42 passes, while consumers treat age as a string.
@IsInt()
age: string;
// The runtime allows undefined, but the type says nickname is always present,
// so downstream code skips the undefined check.
@IsOptional()
@IsString()
nickname: string;
// BUG: no @Type(), so class-transformer leaves this as a plain object
// and AddressDto's rules never run against it.
@ValidateNested()
address: AddressDto;
// Correct: @Type instantiates the nested class, and each: true
// applies validation to every element of the array.
@ValidateNested({ each: true })
@Type(() => ItemDto)
items: ItemDto[];
}
A class-validator DTO that compiles cleanly even though its type annotations disagree with its decorators and one nested property is missing @Type, so its nested rules never run.
How do you implement NestJS Zod validation with a custom pipe?
The pipe is a small class implementing PipeTransform. Its constructor takes a Zod schema, and transform calls schema.safeParse(value). safeParse returns a result object instead of throwing, so the pipe decides what an error looks like. On failure, map each entry in error.issues to a flat record, usually the joined path, the message, and the code, then throw a BadRequestException with that array under a fixed key. Every endpoint then fails with the same shape, and clients don't need to understand Zod's internal error format. On success, return result.data, not the original value. That is how handlers receive the parsed output: unknown keys stripped (the default for z.object), coerced types applied, defaults filled in.
The handler's parameter type comes from z.infer<typeof createUserSchema>. No separate DTO class exists, so the static type cannot drift from the runtime rules.
Per-route versus global
You can attach the pipe per route with @UsePipes(new ZodValidationPipe(schema)), or per parameter with @Body(new ZodValidationPipe(schema)). The parameter form is more precise because @UsePipes runs the pipe against every parameter on the handler. Either way, validation is explicit and local, but it is also opt-in. A new endpoint without the pipe accepts any input, and nothing warns you.
There are three mitigations:
- A lint rule that flags
@Bodyor@Querywithout a pipe argument. - A team convention that reviewers enforce.
- A global pipe. A pipe receives
ArgumentMetadata, not the handler, so it cannot read route decorators directly. The usual approach is to wrap each schema in a class with a staticschemaproperty, use that class as the parameter type, and have the global pipe read the schema frommetadata.metatype. The global pipe should reject any body or query parameter whose type lacks a schema, so a missing schema fails loudly instead of letting input through.
import { BadRequestException, Body, Controller, PipeTransform, Post } from '@nestjs/common';
import { z } from 'zod';
// One schema is the source of truth for runtime rules and the static type.
const createUserSchema = z.object({
email: z.string().email(),
age: z.coerce.number().int().min(13), // "42" from a form becomes 42
role: z.enum(['member', 'admin']).default('member'),
});
type CreateUserDto = z.infer<typeof createUserSchema>;
export class ZodValidationPipe implements PipeTransform {
constructor(private readonly schema: z.ZodType) {}
transform(value: unknown) {
// safeParse returns a result instead of throwing, so we own the error shape.
const result = this.schema.safeParse(value);
if (!result.success) {
throw new BadRequestException({
message: 'Validation failed',
errors: result.error.issues.map((issue) => ({
path: issue.path.map(String).join('.'),
message: issue.message,
code: issue.code,
})),
});
}
// Return parsed data, not the raw input: unknown keys stripped, coercion and defaults applied.
return result.data;
}
}
@Controller('users')
export class UsersController {
@Post()
// Parameter-level pipe: runs only on the body, not on every handler argument.
create(@Body(new ZodValidationPipe(createUserSchema)) body: CreateUserDto) {
return { email: body.email, role: body.role };
}
}
A ZodValidationPipe that maps Zod issues to a consistent BadRequestException payload and returns parsed data. It is attached at the parameter level to a handler whose DTO type comes from z.infer on the same schema.
How should you handle query params, coercion, defaults and unknown fields?
Query strings and path segments reach your pipe as strings, whatever validation library you use. A ?page=2 is "2", and a repeated key such as ?tag=a&tag=b may arrive as an array, depending on the query parser. Neither library can avoid this. What differs is where the conversion happens and how visible it is.
With ValidationPipe, setting transform: true plus enableImplicitConversion lets class-transformer convert values using the reflected TypeScript type. The conversion is invisible at the field level and only as good as the metadata. Booleans are the classic trap: implicit conversion turns "false" into true. In Zod, conversion is written into the schema with z.coerce.number() or a .transform(), and fallbacks with .default(), which only fills in when the value is undefined. This is explicit, but not automatically correct. z.coerce.boolean() has the same "false" problem, and coercing an empty string to a number yields 0. For booleans, prefer an enum of "true"/"false" plus a transform.
Unknown fields are where migrations break without anyone noticing:
| Behaviour | class-validator (ValidationPipe) |
Zod object |
|---|---|---|
| Default | Unknown keys kept | Unknown keys stripped |
| Strip unknown | whitelist: true (global) |
default mode |
| Reject unknown | forbidNonWhitelisted: true |
.strict() |
| Keep unknown | default | .passthrough() |
| Nested objects | follows the pipe option (@ValidateNested, @Type) |
each nested schema sets its own mode |
A global flag becomes a per-schema decision. A nested schema without .strict() will quietly accept fields that used to return a 400.
import { z } from 'zod';
// Query values arrive as strings, so every conversion is written into the schema.
const ListQuery = z.object({
page: z.coerce.number().int().min(1).default(1), // default applies only when the key is absent
limit: z.coerce.number().int().min(1).max(100).default(20),
// Avoid z.coerce.boolean(): Boolean('false') === true
archived: z.enum(['true', 'false']).default('false').transform((v) => v === 'true'),
}).strict(); // the old forbidNonWhitelisted behaviour, set on this schema only
ListQuery.parse({ page: '2', archived: 'false' }); // { page: 2, limit: 20, archived: false }
ListQuery.safeParse({ page: '' }).success; // false: '' coerces to 0, which fails min(1)
ListQuery.safeParse({ debug: '1' }).success; // false: unknown key rejected by .strict()
z.coerce.boolean().parse('false'); // true: the trap the enum above avoids
// .strict() does not cascade. Each nested object picks its own mode.
const CreateUser = z.object({
name: z.string(),
address: z.object({ city: z.string() }), // default mode: unknown keys are stripped
}).strict();
// With forbidNonWhitelisted this was a 400. Here it passes, and zip is silently dropped.
CreateUser.parse({ name: 'Ada', address: { city: 'London', zip: 'N1 9GU' } });
// -> { name: 'Ada', address: { city: 'London' } }
// To keep the old behaviour, mark the nested schema as well:
const CreateUserStrict = z.object({
name: z.string(),
address: z.object({ city: z.string() }).strict(),
}).strict();
CreateUserStrict.safeParse({ name: 'Ada', address: { city: 'London', zip: 'N1 9GU' } }).success; // false
This example uses explicit coercion and defaults for query params, an enum-based boolean that avoids the "false"-to-true trap, and shows that .strict() on a parent schema leaves nested objects in strip mode, where unknown fields are silently dropped instead of rejected.
What does each choice cost for OpenAPI docs, error contracts and shared schemas?
The Swagger module's CLI plugin reads class DTOs at build time and can infer property types and some class-validator constraints, so the docs mostly maintain themselves. Zod schemas are plain values, not classes, so neither the module nor the plugin can see them. You either add a schema-to-OpenAPI bridge or hand-maintain parallel docs classes that can drift. Community bridge packages exist. Evaluate their maintenance, Zod version support and output quality yourself rather than treating any of them as a default.
| Concern | class-validator | Zod |
|---|---|---|
| OpenAPI | Read directly from DTO classes | Needs a bridge or duplicate docs classes |
| Error shape | property plus constraints keyed by rule name, with nested children |
issues[], each with a path array, a code and a message |
| Sharing | Pulls in decorators and reflect metadata | Plain TypeScript with no framework dependency |
| Class behaviour | instanceof, DTO methods, serialization groups |
None of these carry over |
Write one exception filter that normalizes both formats into { field, rule, message }[]. For class-validator, flatten children into dotted paths and emit one entry per constraints key. For Zod, join path with dots and map code to rule. Clients then see one contract during a mixed migration.
In a monorepo, a shared Zod schema saves the frontend from duplicating validation. The cost is coupling. Once the schema is shared, it is a versioned contract, and tightening a field can break every consumer.
Performance depends on schema shape and payload size, so profile your own representative payloads rather than trusting published numbers.
When should you use class-validator, Zod, or something else?
The choice comes down to where your validation rules need to live and who else needs to read them.
| Situation | Prefer | Why |
|---|---|---|
| Service relies on generated Swagger docs and class-based DTOs | class-validator | The Swagger module reads the same classes and decorators, so docs and validation come from one source |
| Validation must run identically for every route, enforced globally | class-validator | A single global ValidationPipe is idiomatic and needs no per-route wiring |
| Request types are shared with a frontend or other services | Zod | A schema in a shared package gives consumers both the runtime check and the inferred type |
| Build tooling strips or mishandles decorator metadata | Zod | Schemas are plain values and do not depend on emitted type metadata |
| Team prefers a different schema-first library | Other validator via custom pipe | The pipe pattern from earlier works the same way, with only the parse call and error mapping changed |
Stay with class-validator if your DTOs are internal to one service and documentation drives your API reviews. Migrating there mostly adds work: you rebuild the OpenAPI integration in exchange for type inference you may not need.
Choose Zod when the schema itself is the product, meaning other codebases import it. It also fits if your compiler or bundler setup has already caused missing-metadata bugs.
Avoid mixing libraries without a clear boundary. Two validators produce two error shapes, two coercion behaviours, and two answers to "what happens to unknown fields?" If you must run both during a transition, split them by module or route prefix and normalize errors in one exception filter. That way clients see a single contract either way.
How do you migrate an existing NestJS codebase from class-validator to Zod?
Migrate in an order where client-visible behavior stays fixed while the internals change.
1. Normalize errors before touching any DTO
Pass a custom exceptionFactory to ValidationPipe, and have the Zod pipe throw the same exception type. One exception filter then renders both into a single body with the same status, field-path format and message structure. If you skip this step, every converted endpoint becomes a breaking API change, even when its rules are identical.
2. Pin current behavior with contract tests
For each endpoint, assert three things against the class-validator version: the error body for representative bad input, the field paths for nested errors, and what happens to unknown fields (stripped, rejected or passed through). Only switch the endpoint once these tests pass. Unknown-field handling is where regressions hide, because whitelist, forbidNonWhitelisted and Zod's strip, strict and passthrough modes don't map one-to-one.
3. Convert one module at a time
Swap DTOs at module boundaries so a shared DTO is never half-converted. Delete the class DTO in the same change that adds the schema. Then add a lint rule that bans class-validator imports in converted modules, so the rules can't live in two places.
4. Watch pipe ordering
Global pipes run before parameter-scoped ones. If a Zod-validated parameter is still typed as a class, a global ValidationPipe with whitelist will strip every undecorated property before Zod sees the input. Type those parameters with the inferred type alias instead.
5. Finish the cutover
Once no module imports class-validator, remove the global ValidationPipe.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nestjs zod validation, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Consumers learn about a breaking change at review time rather than from production errors.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.