Nandhakumar's Display Picture


Dec 2, 2022

6 min read

Nest JS Tutorial #2: HTTP Request & Data Validation






Nest JS Tutorial #2: HTTP Request & Data Validation

Hi There! 👋

In this post, you will learn what is HTTP Request and how to validate the request data in Nest.JS

If you don't know what is Nest JS, Check out my previous post

Let's Get Started Now! 🚀


What is an HTTP Request?

HTTP Request is sent from the client machine(web browser or any other client application) to access or get information from the server.

These Requests are sent with the help of URLs like this 👇

Three parts of HTTP Request

Methods - It defines the type of the request

Headers - It Will have the information about the request and sender(client), you can add custom parameters as well. Usually, Authorization Cookies will be attached to Headers.

Body - It Will have the request data. For example, when registering a new user, you have to pass user information as request data to store it in the server

HTTP Request Methods

HTTP Request Methods

That's a short brief on HTTP Requests.

To know more about HTTP Request, Click Here!

Why Request Data Validation?

As you know the body part of the HTTP Request may have some data.

When the HTTP Request reaches the server, Getting the Body data directly without validating is not good. Sometimes you may get malicious data. So, it is required that you always validate your Request Body data.

Understanding Nest.JS Validation

In Nest.JS, We have something called a validation pipe. Whenever a request body is passed through this pipe and validated. If there are any invalid data, it will throw an error.

Before moving further you need to understand what is DTO(Data Transfer Object)

DTO is a class where you will define the validation rules. If you are not sure about this no worries, you'll understand this when implementing.

Two Parts Of Validation Pipe

Class Transformer -- It helps to transform your request body into a class instance of DTO and then the instance will be passed to the class validation

Class Validator -- It will validate the request body based on the rules defined in the DTO and throws an error if there are any invalid data

Now let's start the implementation for the example scenario given below

Scenario: Need to add a new user and the user should have email, age, name, and country( Country is an optional property).

As per the scenario, it's clear that we need to add data to the server

So, it is an HTTP POST Method and we need to pass user data in the request body.

Hope you have already created a Nest.JS Project, If not follow my previous tutorial to create one.

Now, Let's do the implementation step by step,

Step 1:

Install class validator and class transformer on your project

npm i class-validator class-transformer -s

Step 2:

Generate User Controller.

nest g controller user

Note: to execute nest commands you should have installed nest cli globally

Step 3:

Generate User Module

nest g module user/user --flat

Note: As we have already created a user folder in Step 2, To avoid creating additional folders --flag is used

Step 4:

Add User Controller to User Module

// user.module.ts
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
  imports: [],
  providers: [],
  controllers: [UserController], // add user controller
export class UserModule {}

Step 5:

Add User Module to App Module

// app.module.ts
import { Module } from '@nestjs/common';
import { UserModule } from './user/user.module';

imports: [UserModule], // add user module
controllers: [],
providers: [],
export class AppModule {}

Step 6:

Create a dto folder under the user folder and create a file called user.dto.ts

Project Structure - USER DTO

Step 7:

  • Create UserDTO Class
  • Add the user properties to UserDTO as per the scenario
// user.dto.ts
export class UserDTO {
  email: string;
  age: string;
  name: number;
  country: number;

Step 8:

Nest.JS uses Typescript decorators extensively.

Note: Decorators are a simple function that helps to modify the targeted value Decorators are defined like @decoratorname

Coming back to the UserDTO,

Class-Validator has a list of validation functions which can be used in the form of a decorator

Now, Let's try to add the validation decorators to the class properties

import { IsEmail, IsNumber, IsOptional, IsString } from "class-validator";

export class UserDTO {
  email: string;
  age: string;
  name: number;
  // add @IsOptional to make the country property optional
  country: number;

Step 9:

  • Create a controller to add a user
  • Add UserDTO as the type of the request body
import { Body, Controller, Post } from '@nestjs/common';

import { UserDTO } from './dto/user.dto';
export class UserController {
  async addUser(@Body() user: UserDTO) {
    return user;

Note: I have added @post Decorator to the function addUser as we > are dealing with Post HTTP Request Also, the @Body Decorator to get the request body

Step 9:

Add Validation Pipe middleware globally in main.ts. By adding this globally, it helps DTO to validate the data all over the application.

// main.ts
import { ValidationPipe } from '@nestjs/common'
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
const CookieSession = require('cookie-session')

async function bootstrap() {
  const app = await NestFactory.create(AppModule)

    // By adding this validation pipe globally, nest js helps us to validate body params, query param etc..
    new ValidationPipe({
      whitelist: true, // When Whitelist is set to true, You will not be allowed to send additional props apart from DTO Property

  // Add Cookie Session Middleware to store user id in cookies on the response and the request.
      keys: ['SecretKey'],

That's it we have added validation to the addUser request body


Let's test the implementation now.

Start the server by executing

npm start:dev

Open the server URL http://localhost:3000 in Postman or any API Testing Tool.

Test Case 1

Passing all the user properties with an invalid email

Nest JS Request Body Validation - Test Case 1

And the validation works!

Test Case 2

Since the country property has been set to optional, Now let's try to send the request without the country property

Nest JS Request Body Validation - Test Case 2

Now we got success response, even without the country property.

Try testing with different scenarios by passing invalid data and the validation should work as expected

Congratulation! 👏

You have successfully validated the request body in Nest.JS

Thanks For Reading!

Hope you have learned something new today 😊.

I welcome your questions, feedback, and discussions on this topic. Don't hesitate to reach out if there's something you'd like to talk about.

If you find this post helpful Tweet this Post

Follow and connect with me on Twitter, Instagram, Email and LinkedIn for more interesting stuff like this.

Cheers ✌️