NestJS Request Body

The request body carries data that a client sends to the server — typically when creating or updating a resource. When a user fills out a registration form and clicks submit, the form data travels inside the request body. NestJS extracts this data using the @Body() decorator and makes it available as a typed object in your controller method.

When the Body Is Used

HTTP methods that carry a request body:

Method   | Typical Use
---------|----------------------------------
POST     | Creating a new resource
PUT      | Replacing an entire resource
PATCH    | Partially updating a resource

GET and DELETE requests generally do not have a body. Data for these requests travels as route parameters or query strings instead.

Reading the Full Request Body

Use @Body() without arguments to receive the entire body as an object:

@Post()
create(@Body() body: any) {
  console.log(body);
  // { name: 'Alice', email: 'alice@example.com', age: 30 }
  return this.usersService.create(body);
}

NestJS parses incoming JSON automatically. You do not need to call JSON.parse() manually — the data arrives as a ready-to-use JavaScript object.

Reading a Single Field from the Body

Pass a field name to @Body() to extract just that one property:

@Post()
create(@Body('email') email: string) {
  return `Creating user with email: ${email}`;
}

Using a DTO for the Body

Using any as the body type loses TypeScript's benefits. A DTO (Data Transfer Object) gives you full type safety and enables validation. A DTO is a plain class that describes the expected shape of the body:

// create-user.dto.ts
export class CreateUserDto {
  name: string;
  email: string;
  age: number;
}

// Controller
@Post()
create(@Body() createUserDto: CreateUserDto) {
  return this.usersService.create(createUserDto);
}

Now TypeScript knows exactly what fields createUserDto has. Your IDE gives you autocomplete. If you mistype a field name, TypeScript catches it before the code runs.

Request Body Flow Diagram

Client sends:
POST /users
Content-Type: application/json
Body: { "name": "Alice", "email": "alice@example.com" }

          |
          v
  NestJS parses JSON body
          |
          v
  @Body() createUserDto: CreateUserDto
  { name: 'Alice', email: 'alice@example.com' }
          |
          v
  usersService.create(createUserDto)
          |
          v
  Response: { id: 1, name: 'Alice', email: 'alice@example.com' }

Enabling Body Parsing

NestJS enables JSON body parsing by default. Express's built-in body parser handles JSON and URL-encoded bodies. If your application receives a different content type — like form-data for file uploads — you need additional middleware. File uploads are covered in a dedicated topic later in this course.

Partial Updates with PUT and PATCH

For PUT requests, the client sends a complete replacement body. For PATCH, the client sends only the fields to update. NestJS handles both the same way at the controller level, but your DTO and service logic differ:

// Full replacement (PUT)
export class UpdateUserDto {
  name: string;   // all fields required
  email: string;
  age: number;
}

// Partial update (PATCH)
export class PatchUserDto {
  name?: string;   // all fields optional
  email?: string;
  age?: number;
}

NestJS provides a built-in utility called PartialType that converts all fields of a DTO to optional automatically:

import { PartialType } from '@nestjs/mapped-types';
import { CreateUserDto } from './create-user.dto';

export class UpdateUserDto extends PartialType(CreateUserDto) {}

This single line creates a DTO identical to CreateUserDto but with every field marked optional — exactly what a PATCH endpoint needs.

Combining Body with Other Parameters

A controller method can use multiple parameter decorators at the same time:

@Patch(':id')
update(
  @Param('id') id: string,
  @Body() updateUserDto: UpdateUserDto,
) {
  return this.usersService.update(+id, updateUserDto);
}

The URL (:id) identifies which record to update. The body carries the new values. Both arrive cleanly in the method parameters, each extracted by its own decorator.

Body Validation

Reading the body gives you the raw data the client sent. It does not guarantee the data is valid. A user might send an empty name, a malformed email, or a negative age. NestJS's ValidationPipe combined with class-validator decorators on your DTO handles all validation automatically. That setup is covered in the next few topics. For now, understanding how to read and type the body is the essential first step.

Leave a Comment

Your email address will not be published. Required fields are marked *