How do NestJS pipes validate DTOs in the request lifecycle?

A pipe is a class implementing transform(value, metadata) that NestJS calls once per handler argument. It runs late in the request lifecycle: after middleware, guards and the "before" half of interceptors, and immediately before the route handler. A pipe can return a transformed value, such as a parsed number or a class instance, or it can throw. A thrown exception, usually BadRequestException, skips the handler entirely and goes to exception filters. The metadata argument tells the pipe where the value came from (body, query, param or custom) and which class was declared for it.

Pipes are necessary because TypeScript types do not exist at runtime. Annotating a parameter as CreateUserDto checks nothing about the incoming JSON. The handler receives whatever the client sent, including missing fields, wrong types and extra properties. With emitDecoratorMetadata enabled, the compiler records the declared class constructor, and that is what metadata.metatype exposes. Interfaces and type aliases are erased completely and show up as Object. Any validator that works from the declared type therefore needs a real class.

Pipe scope

Scope decides which routes are actually protected:

  • Global pipes cover every HTTP route. Registering them with app.useGlobalPipes() in main.ts has a catch: an e2e test that builds the app without that bootstrap code runs with no validation. Registering through the APP_PIPE provider keeps the pipe in the module graph, so tests get it too, and it also allows dependency injection.
  • Controller- and method-level pipes (@UsePipes) apply only where you remember to attach them.
  • Parameter-scoped pipes (@Body(new SomePipe())) target a single argument.

Pipes stack in a fixed order: global, then controller, then method, then parameter. A global ValidationPipe combined with a parameter-level validator therefore validates the same body twice. Two validators that disagree, for example on whether unknown keys are stripped, produce confusing results.

 HTTP request (raw JSON: any shape, any types; DTO type is erased)
        v
 +--------------+   +--------+   +-----------------------+
 |  Middleware  |-->| Guards |-->| Interceptors (before) |
 +--------------+   +--------+   +-----------------------+
                                             v
 +--------------------------------------------------------------+
 | Pipes: transform(value, metadata) once per handler argument  |
 |  1 Global       APP_PIPE / useGlobalPipes()  all routes      |
 |  2 Controller   @UsePipes() on class         its routes      |
 |  3 Method       @UsePipes() on handler       one route       |
 |  4 Parameter    @Body(new SomePipe())        one argument    |
 |  metadata.type     = body | query | param | custom           |
 |  metadata.metatype = declared class (interface -> Object)    |
 |  Same pipe registered at two scopes -> it runs twice         |
 +--------------------------------------------------------------+
        |                                    |
   returns value                   throws BadRequestException
        v                                    v
 +------------------------+          +-------------------+
 | Route handler          |          | Exception filters |
 | receives pipe output   |          | (handler skipped) |
 +------------------------+          +-------------------+
        v                                    |
 +----------------------+                    |
 | Interceptors (after) |                    |
 +----------------------+                    |
        +-------> HTTP response <------------+

Pipes run after middleware, guards and the before half of interceptors, immediately before the handler, in global, controller, method and parameter order, and either pass a transformed value to the handler or throw to the exception filters.

How does it work? The two validation models side by side

Both approaches plug into the same pipe slot shown above. They differ in where the rules live and how the pipe finds them.

class-validator with ValidationPipe is metadata-driven:

  1. You declare a DTO class and decorate its properties. The decorators register constraints against that class when the module loads.
  2. At request time, ValidationPipe reads metadata.metatype to learn which class the parameter expects.
  3. class-transformer converts the plain JSON into an instance of that class.
  4. class-validator checks the instance against the registered constraints and returns a list of errors.
  5. If there are errors, the pipe throws BadRequestException. Otherwise it returns the instance (with transform: true) or the original value.

One global pipe can serve every route because the rules travel with each class.

Zod with a custom pipe is schema-driven:

  1. You declare a schema as a value and derive the TypeScript type from it with z.infer.
  2. You bind a pipe instance to that schema, usually per parameter.
  3. The pipe calls safeParse on the raw input. Zod walks the schema, checks types, applies defaults and transforms, and strips or rejects unknown keys.
  4. On failure, the pipe maps the issues to your error format and throws. On success, it returns the parsed output.

The pipe does not consult metadata.metatype, so the parameter type can be a plain type alias. The trade-off is that each route has to be told which schema to use. Nothing happens globally by default.

The sections below cover each model in detail and then compare their behaviour on the cases that usually cause bugs.

How does class-validator work with ValidationPipe?

With ValidationPipe, the DTO class is the schema. You annotate properties with class-validator decorators such as @IsString(), @IsInt(), @Min(1) or @IsOptional(). Those decorators register constraints in a metadata store keyed by the class. TypeScript's emitDecoratorMetadata, read through reflect-metadata, tells Nest which class a handler parameter expects. That is why the parameter type must be a class. An interface or type alias is erased at compile time, so the pipe has nothing to look up and passes the body through unvalidated.

At request time, the pipe calls class-transformer to turn the plain JSON object into an instance of the DTO class. class-validator then checks that instance against the registered constraints. A typical setup registers one pipe globally with app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true })). These options do the following:

  • whitelist strips any property that has no decorator.
  • forbidNonWhitelisted rejects the request with a 400 instead of silently stripping those properties.
  • transform hands the controller the class instance rather than the original plain object.

This model suits teams that already think in classes. It also fits codebases that rely on Swagger decorators living next to validation rules.

The main failure mode is in nested objects. @ValidateNested() only works if class-transformer knows which class to instantiate for the child, and you supply that with @Type(() => AddressDto). Without it, the nested value stays a plain object with no attached metadata. Its fields go unchecked, and whitelist does not strip unknown keys inside it. The request still succeeds, so nothing signals the gap. Arrays of nested DTOs need the same pairing.

// create-user.dto.ts
import { Type } from 'class-transformer';
import { IsInt, IsOptional, IsString, Min, ValidateNested } from 'class-validator';

export class AddressDto {
  @IsString()
  city: string;

  @IsString()
  postcode: string;
}

export class CreateUserDto {
  @IsString()
  name: string;

  @IsInt()
  @Min(1)
  age: number;

  @IsOptional()
  @ValidateNested()
  // Without @Type, address stays a plain object: its fields are never
  // checked and whitelist will not strip unknown keys inside it.
  @Type(() => AddressDto)
  address?: AddressDto;
}

// main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true, // strip properties that have no decorator
      forbidNonWhitelisted: true, // reject them with a 400 instead
      transform: true, // controller receives a CreateUserDto instance
    }),
  );
  await app.listen(3000);
}
bootstrap();

A DTO with a nested AddressDto that relies on both @ValidateNested() and @Type() to be validated, plus a global ValidationPipe using whitelist, forbidNonWhitelisted and transform.

How can you implement a Zod validation pipe in NestJS?

Zod removes that class of gap by removing the decorator layer. A schema is an ordinary value, and z.infer<typeof schema> derives the TypeScript type from it. The runtime check and the compile-time type come from one definition, so they cannot drift apart. Nested objects are validated because they are part of the schema itself. Nothing depends on @ValidateNested or @Type being present.

NestJS does not ship a Zod pipe, so you write one. The usual shape is a class implementing PipeTransform that takes a schema in its constructor. In transform(value, metadata), it calls schema.safeParse(value).

  • On success, it returns result.data, not the original input. This matters because the parsed output carries defaults, transforms and stripped keys. Returning value silently discards that work.
  • On failure, it maps result.error.issues into a fixed structure, typically an array of { path, code, message } with path joined into a dotted string. It then throws a BadRequestException with that structure.

Use safeParse rather than parse so that the pipe decides the error format, not whatever a raw ZodError happens to serialize to.

You can apply the pipe per parameter, for example by passing a new instance with its schema to @Body() or @Query(). You can also attach it to a route with @UsePipes. Per-parameter binding is more precise when a handler reads both body and query.

The pipe is your code. Its error contract, its edge cases (such as the input being undefined) and its tests belong to your team. Keep one implementation in a shared module. If you let each feature module write its own, clients end up handling several slightly different 400 response shapes.

// shared/zod-validation.pipe.ts: one implementation, imported by every module
import { BadRequestException, Injectable, PipeTransform } from '@nestjs/common';
import { z } from 'zod';

@Injectable()
export class ZodValidationPipe<S extends z.ZodType> implements PipeTransform {
  constructor(private readonly schema: S) {}

  transform(value: unknown): z.infer<S> {
    // safeParse never throws, so this pipe controls the error contract
    const result = this.schema.safeParse(value);

    if (!result.success) {
      throw new BadRequestException({
        message: 'Validation failed',
        // Fixed shape for clients: dotted path, Zod issue code, message
        errors: result.error.issues.map((issue) => ({
          path: issue.path.map(String).join('.'),
          code: issue.code,
          message: issue.message,
        })),
      });
    }

    // Return parsed output so defaults, transforms and stripped keys apply
    return result.data;
  }
}

// users/create-user.schema.ts: schema and type come from one value
export const createUserSchema = z.object({
  email: z.string().email(),
  address: z.object({ city: z.string(), zip: z.string() }), // nested, no extra decorators
  role: z.enum(['member', 'admin']).default('member'),
});
export type CreateUserDto = z.infer<typeof createUserSchema>;

// users.controller.ts: bind per parameter
// @Post() create(@Body(new ZodValidationPipe(createUserSchema)) dto: CreateUserDto) {}

A shared ZodValidationPipe calls safeParse, returns the parsed data, and maps Zod issues into one consistent BadRequestException shape. It is bound per parameter to a schema whose TypeScript type is derived with z.infer.

How do unknown keys, nesting and unions differ between the two?

By default the two libraries handle extra keys differently. A Zod z.object() schema strips keys it does not declare, and .strict() turns those keys into a validation error. ValidationPipe does nothing with undeclared properties unless you enable whitelist: true, which removes properties that have no validation decorator. Adding forbidNonWhitelisted: true rejects them instead. If neither option is set, a payload like { "email": "...", "role": "admin" } arrives at your handler unchanged. When that DTO is spread into an ORM create() or update() call, the client can write columns you never meant to expose. This is the classic mass-assignment hole. In either library, rejecting unknown keys is safer than silently stripping them, because a rejection also shows you clients that send the wrong shape.

Nesting is where class-validator needs the most care. A nested AddressDto requires both @ValidateNested() and @Type(() => AddressDto). Arrays use { each: true }. If you leave out @Type, the nested value stays a plain object, its decorators never run, and whitelisting does not apply to it. In Zod, address: AddressSchema is enough, and z.array(ItemSchema) covers arrays. One caveat is that .strict() applies to a single object only, so each nested schema needs its own .strict() call.

Concern class-validator Zod
Unknown keys Pass through unless whitelist Stripped by default
Reject unknown keys forbidNonWhitelisted .strict() per object
Nested objects @ValidateNested() + @Type() Schema composition
Tagged unions class-transformer discriminator option on @Type z.discriminatedUnion()
// --- class-validator style: nested object + array of nested items ---
import { Type } from 'class-transformer';
import { IsEmail, IsInt, IsString, Min, ValidateNested } from 'class-validator';

class AddressDto {
  @IsString() city: string;
  @IsString() postcode: string;
}

class ItemDto {
  @IsString() sku: string;
  @IsInt() @Min(1) qty: number;
}

export class CreateOrderDto {
  @IsEmail() email: string;
  // Without @Type the address stays a plain object: its decorators never run
  // and whitelist/forbidNonWhitelisted do not reach its keys.
  @ValidateNested() @Type(() => AddressDto) address: AddressDto;
  @ValidateNested({ each: true }) @Type(() => ItemDto) items: ItemDto[];
}

// Reject undeclared keys (e.g. "role") instead of passing them through.
// app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));

// --- Zod style: the same payload through composition ---
import { z } from 'zod';

// .strict() applies to one object only, so each nested schema needs its own call.
const AddressSchema = z.object({ city: z.string(), postcode: z.string() }).strict();
const ItemSchema = z.object({ sku: z.string(), qty: z.number().int().min(1) }).strict();

export const CreateOrderSchema = z
  .object({ email: z.string().email(), address: AddressSchema, items: z.array(ItemSchema) })
  .strict(); // { email, ..., role: 'admin' } now fails instead of being stripped

// Tagged union: the 'type' field selects which branch validates the payload.
export const PaymentSchema = z.discriminatedUnion('type', [
  z.object({ type: z.literal('card'), last4: z.string().length(4) }).strict(),
  z.object({ type: z.literal('invoice'), poNumber: z.string() }).strict(),
]);

The same nested order payload validated with class-validator, which needs @ValidateNested plus @Type and forbidNonWhitelisted, and with Zod, which composes schemas, needs .strict() on each object and uses discriminatedUnion for tagged variants.

Why does explicit coercion matter for query and path params?

Everything in req.query and req.params arrives as a string, or as an array of strings when a key repeats. Whatever type the DTO declares, something has to convert that input, and the conversion rules decide what your handler actually receives.

With ValidationPipe({ transform: true, transformOptions: { enableImplicitConversion: true } }), class-transformer reads the TypeScript type from emitted metadata and converts the value using JavaScript's constructors. For booleans that means Boolean("false"), which is true. Any non-empty string is truthy, so ?active=false and ?active=0 both reach your handler as true. Numbers have a similar trap: ?limit= produces Number(""), which is 0. That value passes @IsInt() and @Min(0). None of this conversion appears in the DTO source. It depends on a global flag and on the declared type of each property.

Zod does not remove these traps on its own. z.coerce.boolean() and z.coerce.number() also call Boolean() and Number(), so they produce the same results. The difference is that Zod lets you state the exact rule next to the field:

  • Accept only the literals "true" and "false" and map them to booleans.
  • Reject empty strings before parsing a number.
  • Use .transform() for anything custom.

Because the conversion sits next to the field in the schema, a reviewer can see in the diff exactly which strings are accepted. When a bug report says "active=false returns active users", you look at one line of the schema instead of tracing reflection metadata and pipe options.

The cost is verbosity. Every numeric or boolean query parameter needs its own small parsing rule. Most teams handle this by writing a few shared helpers, such as a query boolean and an optional positive integer, and reusing them across schemas.

What are the trade-offs for OpenAPI, shared contracts and development cost?

Those helpers solve input parsing. The larger costs show up in tooling around the DTO.

Nest's Swagger module builds OpenAPI documents by reading decorators and TypeScript metadata attached to classes. A class-validator DTO is already a class, so adding property decorators keeps the documentation next to the validation rules. A Zod schema is a value, not a class, so the Swagger module has nothing to reflect on. You can add a bridging adapter that converts schemas into OpenAPI definitions, or you can write a parallel class with Swagger decorators. The parallel class causes problems over time. If someone tightens the schema and forgets the decorators, the published contract no longer matches what the server rejects.

Zod has a clear advantage for sharing contracts. A schema is a plain exported value with an inferred type, so a frontend or another service can import the same package and validate against identical rules. Class-validator DTOs carry decorator and reflection dependencies that many client builds don't want.

The value-based approach also has a downside. Zod's parse returns plain objects, so instanceof SomeDto checks fail. Patterns that depend on class instances, such as ClassSerializerInterceptor applying @Exclude rules, silently stop applying.

Concern class-validator Zod
OpenAPI generation Native via class metadata Adapter or duplicated decorators
Sharing with clients Heavy (decorators, reflection) Plain importable values
instanceof / class-based interceptors Works Breaks unless you wrap

Performance depends on how deeply schemas nest, how wide unions are, and how large payloads get. Measure it in your own service rather than assuming one library is faster.

How can the right choice save engineering time?

Most time spent on validation goes to things around the rules rather than the rules themselves: keeping copies of a contract in sync, debugging requests that passed validation but should not have, and handling inconsistent error responses on the client. The choice of approach decides how much of that work you have.

Fewer places to edit per contract change. The cost of a field change is the number of definitions that must change together.

  • With Zod shared between server and client, one schema change updates the runtime check and the inferred type on both sides. The compiler flags every caller that no longer matches.
  • With class-validator and Swagger decorators on the same class, one class change updates validation and documentation together. A frontend that keeps its own hand-written types still needs a separate edit.
  • With Zod plus a parallel Swagger class, you are back to two definitions that can drift.

Fewer silent-failure investigations. The expensive bugs here produce a 200 response instead of an error: a nested object that was never validated because @Type was missing, a false query flag coerced to true, an extra role key passed into an ORM call. Settings that turn these into explicit 400s save debugging time because the failure shows up at the boundary, in a test or in a log, and not later in the data. Useful settings include forbidNonWhitelisted or .strict(), explicit coercion helpers, and schema composition for nesting.

One error contract. A single shared pipe, or a single exceptionFactory, means clients write one error handler. Per-module variations mean every client team handles each variant separately.

Less code you have to own. ValidationPipe is maintained by the framework. A Zod pipe is small, but its tests, edge cases and error mapping belong to you. For a team that will never share types outside the Nest app, owning that code may cost more time than it saves.

An illustrative estimate, using assumed inputs only: suppose a service has 30 request DTOs, each changes on average four times a year, and every change touches a server class, a Swagger definition and a frontend type. That is 30 × 4 × 3 = 360 coordinated edits per year. If a shared schema collapses those three definitions to one, it becomes 120 edits. The real saving depends on how often your contracts change and how much review and testing each edit triggers, so count your own DTOs and change history rather than relying on these numbers.

What are the alternatives to class-validator and Zod?

Neither library is required. NestJS pipes accept any code that validates and transforms a value, so the realistic alternatives are:

  • Nest's built-in parse pipes. @nestjs/common ships ParseIntPipe, ParseBoolPipe, ParseUUIDPipe, ParseEnumPipe and ParseArrayPipe. For a route that takes a single numeric ID or one boolean flag, @Param('id', ParseIntPipe) needs no schema library. ParseBoolPipe accepts only "true" and "false" and rejects other strings, which avoids the implicit-conversion trap described above.
  • Hand-written pipes. A short custom PipeTransform that checks a few fields and throws BadRequestException is easy to read when a route has one or two inputs. It does not scale to large or nested payloads, and every hand-written pipe is another error format to keep consistent.
  • Other schema-validation libraries. Several TypeScript libraries follow the same schema-as-value model as Zod. They plug into Nest through the same kind of custom pipe. Compare them on type inference, error structure, support for unions and refinements, and whether they can produce OpenAPI definitions.
  • JSON Schema with a JSON Schema validator. If your contract already exists as JSON Schema, for example extracted from an OpenAPI document, a pipe can validate against it directly. The schema is language-neutral, which helps when non-TypeScript services share the contract. The trade-off is that TypeScript types must be generated or written separately.
  • Contract-first generation. Some teams write the OpenAPI document first and generate server DTOs, client types and validators from it. This makes the specification the source of truth instead of the code. It adds a build step and depends on the quality of the generator.

The decision guide below focuses on class-validator and Zod, but the same questions apply to any of these: where the source of truth lives, how errors are shaped, and how the choice fits your documentation tooling.

When should you choose class-validator, Zod, or both during migration?

Decision guide

Choose based on where your types originate and how much you rely on Nest's decorator metadata.

Situation Better fit Why
Types defined as classes inside the Nest app, with heavy use of Swagger decorators and class-transformer class-validator The decorators already feed OpenAPI, transformation and validation from one class
Types shared with a frontend or other services Zod One schema yields both the runtime check and the inferred type, with no duplication
Complex unions, refinements or cross-field rules Zod These rules are written directly in the schema, so you avoid custom decorators
Team unwilling to own a custom pipe and error mapping class-validator Less code to maintain yourself
One or two trivial fields Neither A hand-written check in a pipe is clearer than adding a schema

Other schema validators follow the same reasoning. Judge them on type inference, error shape and how well they work with your OpenAPI tooling.

Incremental migration

Scope Zod pipes to individual routes or parameters and keep the global ValidationPipe in place. Nest runs global pipes before route and parameter pipes, so the global pipe sees every Zod route first.

On Zod routes, type the parameter as an inferred type alias, not a class. ValidationPipe skips non-class metatypes. If the parameter is a class with no class-validator decorators, whitelist strips every property from it.

Make both paths return the same error contract. Set an exceptionFactory on ValidationPipe, have the Zod pipe throw the same exception type, and map the issues into one shape, such as field path, message and code. Clients should not be able to tell which validator handled a request.

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.