Controllers

Controllers receive incoming requests and return responses to the client.

Syntax@Controller('prefix')

A controller is responsible for handling incoming requests and sending back responses. Each controller maps to a group of related routes.

How it works

You mark a class with the @Controller() decorator and give it a route prefix. Methods inside become route handlers when decorated with an HTTP method decorator such as @Get().

Controllers should stay thin: their job is to receive input and return output, delegating real work to services.

Example

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

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This returns all cats';
  }
}

When to use it

  • A developer creates a ProductsController to group all HTTP endpoints for the products resource under a single class.
  • A team uses separate controllers (AuthController, UsersController, OrdersController) so each feature's routes are easy to find and test independently.
  • A backend engineer decorates a controller with @UseGuards so every route inside it requires a valid JWT without repeating the guard on each method.

More examples

Minimal controller

Defines a controller that maps GET /cats to the findAll method β€” the simplest controller form.

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

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This returns all cats';
  }
}

Register controller in module

Shows that controllers must be declared in the controllers array of their owning module to be active.

Example Β· ts
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';

@Module({
  controllers: [CatsController],
})
export class CatsModule {}

Controller with injected service

Demonstrates a realistic controller that delegates to a service and accepts a typed body DTO.

Example Β· ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CatsService } from './cats.service';
import { CreateCatDto } from './dto/create-cat.dto';

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get()
  findAll() { return this.catsService.findAll(); }

  @Post()
  create(@Body() dto: CreateCatDto) { return this.catsService.create(dto); }
}

Discussion

  • Be the first to comment on this lesson.