DEV Community

Cover image for Nest JS Tutorial #2: HTTP Request & Data Validation
Nandhakumar
Nandhakumar

Posted on • Updated on

Nest JS Tutorial #2: HTTP Request & Data Validation

Hi There! 👋

In this post, you will learn how to validate request data in Nest JS

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

Originally Posted On - https://www.nandhakumar.io/post/nest-js-tutorial-2-http-request-data-validation

Prerequisite

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 👇



https://yourapp.com/api/v1/users


Enter fullscreen mode Exit fullscreen mode

Three parts of HTTP Request

Methods - Defines the type of the request

Headers - 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 - Will have the requested data. For example, which registering as a new user, you have to pass user information as request data to store it in the server

HTTP Request Methods

Methods Purpose
GET To get Data
POST To create or add data
PATCH To update data partially
PUT To update the entire data
DELETE To delete data

That's a short brief on HTTP Requests.

To know more about HTTP Request, Click Here!

Why Request Data Validation?

When the HTTP Request reaches the server, Getting the Body data directly without validating is not good. Some of you may get malicious data. So, you have to validate your Body data always.

Understanding Nest.JS Validation

Let's first understand how validation works behind the scene in Nest.JS

In Nest.JS, We have something called a validation pipe. Every time when 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 rules for validation. If you are not sure about this no worries, you'll understand this when implementing.

Two Parts Of Validation Pipe

Class Transformer

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

Class Validator

Class Validator 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 optional).

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 would have already created a Nest.JS Project, If not follow my previous tutorial to create one.

Let's do the implementation step by step,

Step 1:

Install class validator and class transformer.



npm i class-validator class-transformer -s


Enter fullscreen mode Exit fullscreen mode

Step 2:

Generate User Controller.



nest g controller user


Enter fullscreen mode Exit fullscreen mode

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

Step 3:

Generate User Module



nest g module user/user --flat


Enter fullscreen mode Exit fullscreen mode

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';
@Module({
  imports: [],
  providers: [],
  controllers: [UserController], // add user controller
})
export class UserModule {}



Enter fullscreen mode Exit fullscreen mode

Step 5:

Add User Module to App Module



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

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


Enter fullscreen mode Exit fullscreen mode

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;
}



Enter fullscreen mode Exit fullscreen mode

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 those validation decorators to the class properties



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

export class UserDTO {
  @IsEmail()
  email: string;

  @IsNumber()
  age: string;

  @IsString()
  name: number;

  // add @IsOptional to make the country property optional
  @IsOptional() 
  @IsString()
  country: number;
}



Enter fullscreen mode Exit fullscreen mode

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';

@Controller('user')
export class UserController {
  @Post()
  async addUser(@Body() user: UserDTO) {
    return user;
  }
}


Enter fullscreen mode Exit fullscreen mode

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

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


Testing

Let's test the implementation now!

Start the server by executing



npm start:dev


Enter fullscreen mode Exit fullscreen mode

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.

Try testing with different scenarios by passing invalid data.

Congratulation! 👏

You have successfully validated the request body in Nest.JS


Thanks For Reading!

Hope you have learned something new today 😊.

Follow me to get notified of all upcoming posts on this series.

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

Top comments (3)

Collapse
 
chungleba profile image
BlackMan

i has answer, import UsePipes, ValidationPipe before. It working !

@Post()
  @UsePipes(new ValidationPipe())
  async addUser(@Body() user: UserDTO) {
    return user;
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
chungleba profile image
BlackMan

i try this but not validate

Image description

Collapse
 
zio-n profile image
Zion

This fixed the issue for me. You have to specify the validationPipe in main.ts so it has a global scope with this

app.useGlobalPipes(new ValidationPipe());
Enter fullscreen mode Exit fullscreen mode