Better Programming

Advice for programmers.

Follow publication

Member-only story

How To Use DTO For Validation in NestJS (2022)

Kevin Vogel
Better Programming
Published in
3 min readFeb 18, 2022

Photo by Fernando Hernandez on Unsplash

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Write a response

Nice article, just a small correction, the `whitelist` option removes all properties of a request's body which do not have validation decorators in the DTO.
If your property exists in the DTO and doesn't have any decorators it will be removed.

That's clear and brilliant Kevin! Didn't know until now the reason of using DTOs on NestJS. I suggest using the `nest g res` command to generate some boilerplate for CRUD resources with DTO classes defined already. Thank you!

I wish writings like this would go just a litttttttle bit more in depth on the topic the whole article revolves around.
You showed us how to incorporate a DTO and use it in a project, but I still don't really know what it is nor how Nest.js interprets and uses it. I'm still a blind little old man here! Help me!