Skip to the content

Lesson 210 of 296

DTOs, validation and configuration

What you will learn

  • What a DTO is
  • Validation with class-validator and ValidationPipe
  • Validation with Zod and Standard Schema in NestJS 12
  • Whitelisting to stop mass assignment
  • Response DTOs and serialisation
  • Configuration with @nestjs/config
  • Generating OpenAPI documentation
On this page

DTOs

A DTO (Data Transfer Object) describes the shape of data that crosses a boundary: a request body coming in, or a response going out. It is separate from your database model, because:

  • Clients should not send or see every database field (IDs, password hashes, internal flags).
  • The API can stay stable while the database changes.
  • Validation rules live on the DTO.

Option 1: class-validator and ValidationPipe

The long-standing NestJS approach: DTO classes with validation decorators:

TypeScript
import { Type } from "class-transformer";
import { IsEmail, IsIn, IsInt, IsOptional, IsString, Length, Max, Min } from "class-validator";

export class CreateCustomerDto {
  @IsString()
  @Length(1, 80)
  name!: string;

  @IsEmail()
  email!: string;

  @IsOptional()
  @IsIn(["free", "pro"])
  plan?: "free" | "pro";

  @Type(() => Number)
  @IsInt()
  @Min(0)
  @Max(120)
  age!: number;
}

Enable validation globally:

app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
OptionEffect
whitelist: trueRemoves properties that have no decorator: stops mass assignment (a client sending "role":"admin", Lesson 196)
forbidNonWhitelisted: trueInstead of removing, rejects the request with 400
transform: trueTurns the plain object into a DTO class instance and converts types (with @Type)

Invalid input gets a 400 with a list of messages. NestJS 12 adds an errorFormat option ("list" or "grouped") to control the shape of these errors. Classes are needed (not interfaces) because the decorators must exist at runtime.

Option 2: Zod with Standard Schema (NestJS 12)

Standard Schema is a shared interface that validation libraries (Zod, Valibot, ArkType) implement. NestJS 12 supports it directly in route decorators: you pass a schema, and a global StandardSchemaValidationPipe validates it. One schema gives you both the runtime check and the TypeScript type (Lesson 114):

TypeScript
import { Body, Controller, Get, Param, Post } from "@nestjs/common";
import { z } from "zod";

export const CreateProductSchema = z.strictObject({
  name: z.string().trim().min(1).max(120),
  pricePence: z.number().int().positive(),
  tags: z.array(z.string()).max(10).default([])
});
export type CreateProductDto = z.infer<typeof CreateProductSchema>;

@Controller("products")
export class ProductsController {
  @Post()
  create(@Body({ schema: CreateProductSchema }) body: CreateProductDto) {
    return { created: body };
  }

  @Get(":id")
  findOne(@Param("id", { schema: z.coerce.number().int().positive() }) id: number) {
    return { id, typeOfId: typeof id };
  }
}

And in main.ts: app.useGlobalPipes(new StandardSchemaValidationPipe());.

  • z.strictObject rejects unknown keys (mass assignment protection); z.object would silently strip them.
  • z.coerce.number() turns the route parameter string into a number.
  • The same schema can be shared with the front end (React Hook Form, Lesson 174) in a monorepo, so the rules never drift apart.
  • In NestJS 11 and earlier, teams used a small custom ZodValidationPipe or the nestjs-zod library for the same result.
class-validatorZod / Standard Schema
StyleDecorators on classesSchema objects
TypesClass doubles as the typez.infer from the schema
Sharing with the front endAwkwardEasy
EcosystemLong-established in Nest docs and older projectsGrowing fast; first-class in NestJS 12

Know both: you will meet class-validator in most existing NestJS codebases.

Response DTOs and serialisation

Never return database entities directly; they may contain secrets. Options:

  • Map explicitly in the service: return { id: user.id, email: user.email };.
  • ClassSerializerInterceptor with @Exclude() on fields of a class.
  • In NestJS 12, StandardSchemaSerializerInterceptor with @SerializeOptions({ schema: UserResponseSchema }), which shapes the output with a schema.

Configuration

@nestjs/config loads environment variables and .env files and provides a ConfigService. Validate them at start-up (Lesson 193):

ConfigModule.forRoot({
  isGlobal: true,
  validate: (env) => EnvSchema.parse(env)
})

Then inject ConfigService and read config.get("DATABASE_URL", { infer: true }). In NestJS 12, validationSchema also accepts any Standard Schema library directly. For larger apps, namespaced config (registerAs("database", () => ({...}))) groups settings by feature.

OpenAPI documentation

@nestjs/swagger generates an OpenAPI document (Lesson 196) from your controllers and DTOs, and serves Swagger UI at a path such as /docs. Decorators like @ApiProperty(), @ApiResponse() and @ApiBearerAuth() add detail; a CLI plugin can infer much of it automatically. In NestJS 12, Standard Schema schemas can feed OpenAPI generation too.

How to say it in an interview

"DTOs define the shape of data crossing the API boundary, separate from database models. With class-validator I decorate DTO classes and use a global ValidationPipe with whitelist and forbidNonWhitelisted to block mass assignment, and transform to convert types. In NestJS 12 I can pass a Zod schema to Body, Query or Param through Standard Schema support with the StandardSchemaValidationPipe, which gives the runtime check and the TypeScript type from one schema that I can share with the front end. I shape responses explicitly or with a serializer so secrets never leak, validate configuration at start-up with @nestjs/config, and generate OpenAPI docs from the code."

Key words

WordMeaning
DTOData Transfer Object: the shape of data crossing a boundary
class-validatorDecorator-based validation for classes
ValidationPipeNest pipe that validates DTO classes
whitelistStrip properties without validation decorators
Standard SchemaA shared interface implemented by Zod and other validators
SerialisationTurning objects into the response format, removing hidden fields
ConfigServiceNest's injectable access to configuration

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.