Request & Response Data

Read the request body with @Body and, when needed, access the raw response object.

Syntax@Body() body / @Res() res

To read the JSON a client sends, use the @Body() decorator. Nest parses the request body for you.

Preferred: let Nest handle responses

Return a value from your handler and Nest serializes it to JSON with the right status code. This is the recommended, platform-independent approach.

Escape hatch

You can inject the underlying response with @Res(), but doing so opts you out of Nest's automatic handling. Prefer returning values instead.

Example

Example Β· typescript
import { Controller, Post, Body } from '@nestjs/common';

@Controller('messages')
export class MessagesController {
  @Post()
  create(@Body() body: { text: string }) {
    // Just return an object - Nest sends it as JSON
    return { received: body.text, id: 1 };
  }
}

When to use it

  • A developer uses @Body() to deserialize the JSON payload from a POST /users request directly into a CreateUserDto class.
  • A developer uses @Headers("authorization") to read the raw Authorization header value before passing it to an auth service.
  • A team injects the raw @Res() object on a file-download endpoint to call res.download() which NestJS does not wrap natively.

More examples

Reading the request body

Shows @Body() deserializing the JSON request body into a typed DTO instance.

Example Β· ts
import { Controller, Post, Body } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';

@Controller('users')
export class UsersController {
  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return createUserDto;   // body is deserialized automatically
  }
}

Reading a specific header

Demonstrates @Headers() to access a specific HTTP header directly in the handler signature.

Example Β· ts
import { Controller, Get, Headers } from '@nestjs/common';

@Controller('profile')
export class ProfileController {
  @Get()
  getProfile(@Headers('authorization') auth: string) {
    return { auth };   // raw 'Bearer <token>' string
  }
}

Using raw response object

Injects the raw Express Response to call platform-specific methods like res.download() that NestJS does not abstract.

Example Β· ts
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller('files')
export class FilesController {
  @Get('report')
  download(@Res() res: Response) {
    res.download('/tmp/report.pdf');
  }
}

Discussion

  • Be the first to comment on this lesson.