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:
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 }));| Option | Effect |
|---|---|
whitelist: true | Removes properties that have no decorator: stops mass assignment (a client sending "role":"admin", Lesson 196) |
forbidNonWhitelisted: true | Instead of removing, rejects the request with 400 |
transform: true | Turns 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):
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.strictObjectrejects unknown keys (mass assignment protection);z.objectwould 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
ZodValidationPipeor thenestjs-zodlibrary for the same result.
| class-validator | Zod / Standard Schema | |
|---|---|---|
| Style | Decorators on classes | Schema objects |
| Types | Class doubles as the type | z.infer from the schema |
| Sharing with the front end | Awkward | Easy |
| Ecosystem | Long-established in Nest docs and older projects | Growing 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 };. ClassSerializerInterceptorwith@Exclude()on fields of a class.- In NestJS 12,
StandardSchemaSerializerInterceptorwith@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
| Word | Meaning |
|---|---|
| DTO | Data Transfer Object: the shape of data crossing a boundary |
| class-validator | Decorator-based validation for classes |
| ValidationPipe | Nest pipe that validates DTO classes |
| whitelist | Strip properties without validation decorators |
| Standard Schema | A shared interface implemented by Zod and other validators |
| Serialisation | Turning objects into the response format, removing hidden fields |
| ConfigService | Nest's injectable access to configuration |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.