Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 42 ยท Controllers and Routing

Reading Request Data

Read request data in NestJS with @Param, @Query, @Body and @Headers, model payloads with DTO classes, shape responses, and avoid the @Res and @Req pitfalls.

A route is only useful if it can see what the client sent: the id in the path, the filters in the query string, the JSON in the body, the headers. In Express you dig these out of a req object. In Nest you ask for each piece with a parameter decorator, and Nest passes in exactly that value. The method signature then documents what the endpoint needs.

This lesson covers the request decorators, DTO classes for request bodies, how return values shape the response, and why reaching for the raw response object with @Res() is usually a mistake. The real Nest code is read-only here. The stand-ins show how an argument extractor turns decorator metadata into method arguments, which is the heart of how Nest works.

The parameter decorators

TypeScript
import { Controller, Get, Post, Body, Param, Query, Headers } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  // GET /cats/7?verbose=true
  @Get(':id')
  findOne(
    @Param('id') id: string,
    @Query('verbose') verbose?: string,
    @Headers('user-agent') agent?: string,
  ) {
    return { id, verbose, agent };
  }

  // POST /cats with a JSON body
  @Post()
  create(@Body() body: CreateCatDto) {
    return body;
  }
}
  • @Param('id') reads one route parameter, and @Param() with no name gives all of them as an object.
  • @Query('verbose') reads one query string value, and @Query() gives the whole parsed object.
  • @Body() gives the parsed request body, and @Body('name') picks one property.
  • @Headers('user-agent') reads one header (names are lowercase), and @Headers() gives all headers.
  • @Req() gives the underlying platform request, and @Ip() gives the client IP.

Remember that every value from the URL is a string. @Param('id') id: string gives '7', not 7, and a TypeScript annotation of number does not convert it. Real conversion is done by pipes, covered in Pipes and Validation; for example, @Param('id', ParseIntPipe) id: number converts and rejects values that are not integers.

Where does each value come from?

@Param The path, like /cats/7.
@Query The query string, like ?page=2.
@Body The JSON payload of POST and PUT.
@Headers Metadata like authorization.

Every value from the URL starts as a string.

1 / 2

How the extractor works

Parameter decorators do not run when a request arrives. At startup they record "argument 0 of findOne is the route parameter id". On every request Nest reads that record, builds the argument list from the request and calls the method. The stand-in below does the same with an explicit list.

Node.js An argument extractor driven by parameter metadata

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output shows two things. The id arrives as the string "7", exactly as it would in Nest without a pipe. And the controller code contains no request parsing at all: it is a plain method with plain arguments, which is why Nest controllers are easy to unit test.

DTO classes

For request bodies, Nest uses a DTO (data transfer object): a class that describes the shape of the payload.

TypeScript
export class CreateCatDto {
  name: string;
  age: number;
  breed?: string;
}

Use a class, not an interface or a type alias. Interfaces disappear at compile time, so Nest has nothing to inspect at runtime. A class survives compilation, which is what lets the validation and transformation pipes check and convert incoming data against it (see Pipes and Validation). Keep a separate DTO per use: CreateCatDto for creation and UpdateCatDto for changes, where most fields are optional.

Note that a TypeScript type on @Body() body: CreateCatDto is only a promise to the compiler. Without a validation pipe, a client can send anything, and the object you receive may be missing fields or have extra ones. Never trust DTO types alone for security.

Shaping the response

Nest turns whatever your method returns into the response. You can shape it by controlling what you return:

TypeScript
@Get(':id')
findOne(@Param('id') id: string) {
  const cat = this.cats.find(id);
  return { data: cat, fetchedAt: new Date().toISOString() };
}

In practice, shape responses in one place instead of in each method. A response DTO class, a serializer or an interceptor can wrap every response in the same envelope and hide fields such as password hashes. Never return a database entity that contains secrets and hope the client ignores them.

The @Res pitfall

@Req() and @Res() give you the raw Express (or Fastify) objects. That feels familiar, but there is a trap: as soon as you inject @Res(), you are responsible for sending the response, and Nest stops doing it for you. The value you return is ignored, and features that depend on Nest handling the response, such as interceptors that map results and @HttpCode(), stop working as expected. Your code is also tied to one platform.

TypeScript
// Takes over the response: the return value is ignored
@Get('a')
manual(@Res() res: Response) {
  res.status(200).json({ ok: true });
}

// Better: keep Nest in charge, but still touch the response
@Get('b')
passthrough(@Res({ passthrough: true }) res: Response) {
  res.cookie('seen', '1');
  return { ok: true };
}

With { passthrough: true } you may set headers or cookies on the platform response and still return a value. The stand-in below reproduces both behaviors with a "response handled by the handler" flag, and shows an envelope that hides sensitive fields.

Node.js Return values, @Res takeover and response shaping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If you do take over the response with @Res() and forget to send anything, the request hangs until the client times out. If you only need a header or cookie, use { passthrough: true }.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type does @Param('id') give you for the request GET /cats/7 when no pipe is used?

    URL values are always strings. A TypeScript annotation does not convert them; a pipe such as ParseIntPipe does.
  2. 2. Why should a DTO be a class instead of an interface?

    Classes exist at runtime, so validation and transformation pipes can use them. Interfaces vanish during compilation.
  3. 3. What happens to the returned value when a handler injects @Res() without passthrough?

    With @Res() you take over response handling. Use { passthrough: true } to keep Nest's normal return handling.
  4. 4. Which decorator reads the whole parsed query string as an object?

    @Query() with no key gives the parsed query object, and @Query('key') gives a single value.

Summary

  • Parameter decorators such as @Param, @Query, @Body and @Headers record where each method argument comes from; Nest builds the arguments on every request.
  • Values from the URL are strings; use pipes to convert and validate them.
  • Describe request bodies with DTO classes (not interfaces), and keep separate create and update DTOs.
  • A TypeScript type on @Body() is not validation; add a validation pipe.
  • Shape responses in one place and never return entities that contain secrets.
  • Prefer returning values over @Res(); use { passthrough: true } if you only need to set headers or cookies.
  • The stand-ins use an explicit metadata list; real Nest fills the same list from decorators.

Next: Providers and Dependency Injection