DTOs
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 13 of 24.
@Body() body: { title: string } describes the body in one place only, and nothing checks it: { "title": 42 } goes straight through. A DTO, a data transfer object, is a class that describes what a request body holds.
export class CreateOrderDto {
customer: string;
express?: boolean;
}
@Post()
create(@Body() dto: CreateOrderDto) {
return this.ordersService.create(dto);
}express? marks an optional field. The controller and the service share the class, so they agree on the shape.
A DTO is a class, not an interface, for a reason. Interfaces are removed with the other types when the code runs, while a class still exists. Nest's validation reads rules written as decorators, and decorators need a class. That is the next lesson.
Challenge
EasyClients may now create a task that is already done. Describe the body of POST /tasks with a DTO, a class that lists the fields a request body holds, and pass it all the way to the service.
- In
src/tasks/dto/create-task.dto.ts, give the classCreateTaskDtotwo fields:title, a string, anddone, an optional boolean. - In
src/tasks/tasks.controller.ts, change thecreatemethod. Its@Body()parameter now has the typeCreateTaskDtoinstead of{ title: string }. Pass the whole DTO to the service, not only the title. - In
src/tasks/tasks.service.ts, changecreateto take the DTO instead of a title. The new task gets itstitlefrom the DTO, and itsdonefrom the DTO too, orfalsewhen the body has nodone. The id andcreatedAtwork as before.
Try it: POST { "title": "Pay rent", "done": true } to /tasks. You get 201 and the new task, finished:
{ "id": 4, "title": "Pay rent", "done": true, "createdAt": "2026-10-30T09:15:00.000Z" }(createdAt shows the time of your request.) POST { "title": "Buy milk" }: 201 with "done": false. Then POST { "title": 42 }. You still get 201, with "title": 42 saved: the DTO describes the body but checks nothing yet. The next lesson makes Nest refuse it.
Try it yourself
// Describe the body of POST /tasks: a title, and done when the client sends it.
export class CreateTaskDto {}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in TypeScript and NestJS
Practice on your own: Express playground