Member-only story
How To Use DTO For Validation in NestJS (2022)
Know how DTO works in NestJS
Today I’ll talk about Data Transfer Objects (DTO) in NestJS and how to use them in order to validate your incoming requests.
What is a DTO?
The DTO on its own is more of a guideline for the developer and those who consume the API to know what kind of shape the request body expects to be, it doesn’t actually run any validations on its own.
However, with TypeScript, you can add in decorators from the class-validator library using the built-in Validation Pipe and have validations run on your incoming requests so that only the expected request body can come in.
Prerequisites
It’s required to have a basic understanding of Node.js and TypeScript. I will choose Visual Studio Code as my code editor. You can use whatever you prefer.
Let’s get started
First, we are going to install the NestJS CLI, so open the terminal of your choice and type:
$ npm i -g @nestjs/cli
We initialize a new NestJS project with its CLI. That might take up to a minute. The CLI script will ask you what package manager you want to use. For this example, I select NPM.