API Request Validation in NestJS
Request Validation is one of the most overlooked aspects of API development, and yet it remains a crucial component of our applications. It might feel cumbersome at first: some might even view it as an “extra coding effort”, but validation is something that will add an extra layer of security to your APIs, by validating the correctness of data being sent as input and reducing the chance of security vulnerabilities.
In this blog, we’ll understand how to leverage the power of data validation in a NestJS application.

For the uninitiated, NestJS is a powerful Node.js framework for building Typescript-based server-side applications. NestJS offers built-in support for request validation, which helps in enforcing data integrity. It enables the developers to verify that the data being sent to API endpoints meets certain predefined criteria, before processing it further. This ensures that application will only receive the data that it expects, and the rest of the data will be discarded, thereby preventing any malicious/malformed data from disrupting the application.
Getting started with Request Validation
DTOs (Data Transfer Objects) can come in handy if one needs to validate a schema in NestJS. To start with, let’s create a simple DTO to specify the format of request body while creating a new user:
export class CreateUserDto {
name: string;
email: string;
role: string;
}
Now this DTO alone can’t do much, as it will merely check if the listed fields are present in the request body. But adding Decorators can further enhance this DTO, by making sure that the data is correctly formatted and also allowing to transform the data if required.
NestJS and
class-validator
library make a perfect combo when it comes to request validation in Typescript-based applications.
class-validator
brings in certain decorators which can come in handy for schema-based validation. It also empowers the developers to create custom decorators to suit their specific requirements.
In order to enrich our DTO with decorators, the first step is to install the required dependencies:
npm install class-validator --save
Now let’s enhance our CreateUserDTO
with some decorators:
import {
IsNotEmpty,
IsString,
IsEmail,
IsStrongPassword
} from 'class-validator';
export class CreateUserDto {
@IsString()
@IsNotEmpty()
name: string;
@IsEmail()
@IsNotEmpty()
email: string;
@IsStrongPassword()
@IsNotEmpty()
password: string;
@IsString()
@IsNotEmpty()
role: string;
}
This enhanced CreateUserDto
comes with an extra layer of validation which will make the API more robust, secure and reliable.
The CreateUserDto
can now be easily used to validate the incoming request for an API in the Controller layer.
import { Controller, Post, Body } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
// further imports
@Controller('users')
export class UsersController {
@UsePipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
}),
)
@Post('/')
async createUser(@Body() body: CreateUserDto) {
// logic to create a user by calling a function of service layer
}
}
Here, ValidationPipe
has been used to automatically apply validation on incoming request payloads, based on the validation rules defined in the DTO. ValidationPipe
also has certain options like whitelist
, forbidNonWhitelisted
etc., which can be configured as per the requirement. You can read more about these options here.
In order to automatically apply this validation behaviour to all the APIs at module level or global level, useGlobalPipes
is used.
app.useGlobalPipes(
new ValidationPipe({
forbidUnknownValues: true,
}),
);
That’s it for this blog. Feel free to check out my other blogs to further expand your knowledge on NestJS!