Skip to main content
Practice Problems

What are controllers in NestJS?

NestJS Controllers

Controllers handle incoming HTTP requests and return responses. They are the entry point for any request in a NestJS application. Controllers are decorated with @Controller() and their methods use HTTP method decorators like @Get(), @Post(), etc.


Basic Controller

typescript
import { Controller, Get, Post, Put, Delete, Patch, Param, Body, Query, HttpCode, HttpStatus } from '@nestjs/common'; import { UsersService } from './users.service'; import { CreateUserDto } from './dto/create-user.dto'; @Controller('users') // route prefix: /users export class UsersController { constructor(private readonly usersService: UsersService) {} @Get() findAll(@Query('page') page = 1) { return this.usersService.findAll({ page }); } @Get(':id') findOne(@Param('id') id: string) { return this.usersService.findOne(+id); } @Post() @HttpCode(HttpStatus.CREATED) create(@Body() createUserDto: CreateUserDto) { return this.usersService.create(createUserDto); } @Put(':id') update(@Param('id') id: string, @Body() updateUserDto: CreateUserDto) { return this.usersService.update(+id, updateUserDto); } @Delete(':id') @HttpCode(HttpStatus.NO_CONTENT) remove(@Param('id') id: string) { return this.usersService.remove(+id); } }

Parameter Decorators

DecoratorDescription
@Param('id')URL parameter: /users/:id
@Query('page')Query string: /users?page=2
@Body()Full request body
@Body('name')Single body field
@Headers('authorization')Request header
@Req()Full Express request object
@Res()Full Express response object
@Ip()Client IP address
@HostParam()Host parameter

Route Wildcards and Versioning

typescript
@Controller({ path: 'users', version: '1' }) // /v1/users export class UsersV1Controller {} @Get('ab*cd') // matches abcd, ab_cd, abecd, etc. @Get(':id/posts') // /users/42/posts

Returning Responses

typescript
// Default: NestJS serializes return value to JSON automatically @Get() findAll() { return [{ id: 1 }]; // → 200 { ... } } // Custom status code @Post() @HttpCode(201) create() { ... } // Using @Res() for manual control (disables NestJS response handling!) @Get() findAll(@Res() res: Response) { return res.status(200).json({ data: [] }); } // Async is fully supported @Get(':id') async findOne(@Param('id') id: string) { return await this.usersService.findOne(+id); }

Route Prefixes & Global Prefix

typescript
// main.ts — prefix all routes with /api/v1 app.setGlobalPrefix('api/v1'); // GET /api/v1/users, POST /api/v1/users, etc.

Summary

Controllers in NestJS are decorated classes that map HTTP requests to handler methods. They only handle request routing and delegate business logic to services. Use parameter decorators to extract data from requests, and HTTP method decorators to define route handlers.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems