In a NestJS controller, how do @Controller, @Get, @Post, @Param, @Query and @Body turn an HTTP request into a handler call?
answer
- prefix plus method path
- parameter decorators read req
- path and query values are strings
- return value becomes the body
- 200, or 201 for POST
basics
~20 s@Controller('users') sets a path prefix and @Get(':id') or @Post() adds the HTTP method and sub-path. Nest fills arguments from @Param, @Query and @Body, then sends the return value, as JSON for objects, with status 200, or 201 for POST.
solid answer
~40 sA route is the controller prefix plus the method decorator's path: `@Controller('users')` with `@Get(':id')` maps `GET /users/:id`; the method's name means nothing to Nest. The controller must be listed in a module's `controllers` array or Nest never instantiates it. Parameter decorators pull pieces of the request into arguments: `@Param('id')` reads `req.params.id`, `@Query('page')` one query key, `@Body()` the parsed body, `@Headers('x-request-id')` a header. Path and query values arrive as **strings**; a `number` annotation does not convert them, a pipe such as `ParseIntPipe` does. The handler simply returns: objects and arrays are serialized to JSON, primitives are sent as they are, and the status is 200, except 201 for `@Post()`, unless `@HttpCode()` says otherwise.
code
typescript · 20 linesimport { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import { CreateUserDto } from './create-user.dto.js';
@Controller('users')
export class UsersController {
@Get()
list(@Query('page') page?: string) {
return { page: page ?? '1' }; // GET /users?page=2 -> { page: '2' }
}
@Get(':id')
findOne(@Param('id') id: string) {
return { id }; // GET /users/42 -> { id: '42' }, status 200
}
@Post()
create(@Body() dto: CreateUserDto) {
return dto; // POST /users -> status 201
}
}go deeper
Recall how the controller prefix and the method decorator's path combine, which decorator reads params, query and body, and the 200 versus 201 default.
Explain why path and query values stay strings despite a type annotation, and why DTOs are classes rather than interfaces.
Point out the failure modes a review should catch: unregistered controllers, parametric routes declared before literal ones, and fixed statuses that should come from exceptions.
Decide how far a team leans on decorators versus the raw response object, since that choice sets how portable and testable controllers stay.
## The route a decorator builds In NestJS a **controller** is a class whose methods handle HTTP requests. Two decorators define where a method listens: - **`@Controller(prefix)`** on the class sets an optional path prefix shared by every route in it, such as `'users'`. - **A method decorator** such as `@Get()`, `@Post()`, `@Put()`, `@Patch()`, `@Delete()`, `@Options()`, `@Head()` or `@All()` sets the HTTP method and an optional sub-path. The full route is the prefix joined with the sub-path. `@Controller('users')` plus `@Get(':id')` maps `GET /users/:id`; `@Post()` alone maps `POST /users`. The method's own name is arbitrary: Nest binds the route to whatever method carries the decorator. A segment that starts with a colon, such as `:id`, is a **route parameter** that captures one path segment. A controller only takes effect once it is listed in the `controllers` array of a module's `@Module()` decorator. A forgotten registration produces no error at all, just a 404 for every route in the class. ## Mapping request parts to arguments Parameter decorators tell Nest which part of the underlying request object to pass into each argument: | Decorator | What the argument receives | |---|---| | `@Param()` / `@Param('id')` | `req.params` / `req.params.id` | | `@Query()` / `@Query('page')` | `req.query` / `req.query.page` | | `@Body()` / `@Body('name')` | `req.body` / `req.body.name` | | `@Headers()` / `@Headers('x-request-id')` | `req.headers` / one header | | `@Req()`, `@Res()` | the platform's raw request and response objects | | `@Ip()`, `@HostParam()` | `req.ip`, the captured host parameters | Three details catch people out: 1. **Values from the path and the query string are strings.** `@Query('age') age: number` still receives `'2'` for `?age=2`; a TypeScript annotation is erased at compile time and converts nothing. A pipe such as `ParseIntPipe` performs the conversion; how pipes validate and transform is covered with Nest's pipes. 2. **Use a class, not an interface, for a body DTO.** Classes survive compilation, so pipes can read the parameter's metatype at runtime; interfaces vanish. 3. **Without a key, the decorator passes the whole object.** `@Param()` gives you all route parameters, `@Query()` the whole parsed query. ## What the handler returns In Nest's standard response mode, the handler just returns a value, a `Promise` or an RxJS `Observable`, and Nest writes the response: - an object or array is serialized to JSON; - a string, number or boolean is sent without serialization; - the status code is **200**, except **201** for `@Post()` handlers; - `@HttpCode(204)` on the method changes that fixed status, and `@Header('Cache-Control', 'no-store')` adds a static header. An error status comes from throwing an exception, which Nest's exception layer turns into a response. ## Async handlers, wildcards and every method A handler does not have to return a plain value: - **`async` handlers** return a `Promise`; Nest awaits it and sends the resolved value, so `async findAll() { return this.users.list(); }` needs nothing extra. - **RxJS `Observable` results** are subscribed to internally; Nest sends the last emitted value once the stream completes. - **Wildcards**: `@Get('files/*')` matches every path under `files/`. Plain Express 5 insists on a named wildcard such as `{*splat}`, but Nest's compatibility layer for the Express adapter still accepts the unnamed asterisk at the end of a path. - **`@All()`** registers one handler for every HTTP method on that path, which is occasionally useful for a catch-all proxy route and otherwise a source of surprises. Because the decorators only attach metadata, a controller that sticks to return values and parameter decorators, rather than the raw response object, moves between the Express and Fastify adapters with little or no change. ## Registering and checking ```typescript @Module({ controllers: [UsersController], providers: [UsersService] }) export class UsersModule {} ``` At startup Nest logs one "Mapped {/users/:id, GET} route" line per route, which is the quickest way to confirm that a controller is registered and that the prefix and sub-path joined as you expected. ## Common mistakes - Expecting `@Query('limit') limit: number` to be a number without a pipe. - Declaring `@Get(':id')` before a literal `@Get('me')` on the Express adapter, where the first registered match wins. - Forgetting to add the controller to a module's `controllers` array. - Typing the body as an interface and then wondering why validation sees no metadata.
- How do you return 204 from a NestJS @Delete() handler that has nothing to send?Add `@HttpCode(204)` to the method and return nothing. `@HttpCode()` sets a fixed status for the route; a status that depends on runtime conditions instead comes from throwing an exception or, as a last resort, from the library response object.
- Why does the controller's method name not matter to Nest's routing?The route comes from decorator metadata: the class prefix and the method decorator's path. Nest reads that metadata and binds the route to whichever method carries it, so `findOne` and `getById` behave identically; the name only matters to readers and to the handler label in logs.
- A number type annotation makes Nest convert @Query and @Param values.
- The handler method name has to match the route path.
- A @Post() handler returns status 200 unless you set it.
- Controllers are discovered automatically without being listed in a module.
- An interface works just as well as a class for a body DTO.