Controllers in NestJS

Danimai
3 min readApr 2, 2024

Controllers play a crucial role in any web application, as they act as the intermediary between the client’s requests and the server’s responses. In NestJS, controllers serve as the primary mechanism for handling incoming requests and executing the appropriate logic to generate responses. In this guide, we’ll delve into the core concepts of controllers in NestJS, including basic routing, important decorators for request handling functions, redirection, and handling request payloads.

Basic Routing with Controllers

NestJS employs a modular approach to organize your application’s codebase. Controllers are essentially classes responsible for handling incoming requests from specific routes and generating responses. Let’s start by creating a basic controller in NestJS:

// cats.controller.ts

import { Controller, Get } from '@nestjs/common';

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

In the above example, we’ve created a simple controller named CatsController with a single route handler for the GET /cats endpoint. The @Controller() decorator specifies the base route path for all routes defined within the controller.

Important Decorators for Request Handling Functions

NestJS provides several decorators to define the behavior of request handling functions within controllers. Some important decorators include:

  • @Get(): Defines a route handler for HTTP GET requests.
  • @Post(): Defines a route handler for HTTP POST requests.
  • @Put(): Defines a route handler for HTTP PUT requests.
  • @Delete(): Defines a route handler for HTTP DELETE requests.
  • @Param(): Retrieves route parameters.
  • @Query(): Retrieves query parameters.
  • @Body(): Retrieves the request body.

Here’s an example demonstrating the usage of these decorators:

// cats.controller.ts
import { Controller, Get, Post, Param, Body } from '@nestjs/common';

@Controller('cats')
export class CatsController {
@Get(':id')
findOne(@Param('id') id: string): string {
return `This endpoint returns cat with id ${id}`;
}

@Post()
create(@Body() catData: any): string {
return `This endpoint creates a new cat with data: ${JSON.stringify(catData)}`;
}
}

In the above example, we’ve defined two route handlers using the @Get() and @Post() decorators, along with @Param() and @Body() decorators to retrieve route parameters and request body, respectively.

Redirection

Redirecting requests to another route is a common requirement in web applications. NestJS provides a Redirect method from @nestjs/common package to perform redirection. Here's an example of how to use redirection in a controller:

// cats.controller.ts
import { Controller, Get, Redirect } from '@nestjs/common';

@Controller('cats')
export class CatsController {
@Get('docs')
@Redirect('https://nestjs.com', 302)
redirectToDocs() {
// This method will not be executed because of the redirection
}
}

In the above example, accessing the GET /cats/docs endpoint will automatically redirect the request to https://nestjs.com with a status code of 302.

Request Payloads

Handling request payloads is essential for processing data sent from clients to the server. NestJS simplifies this process using the @Body() decorator, as demonstrated earlier. You can also apply validation using various validation libraries like class-validator.

// create-cat.dto.ts

import { IsString, IsInt } from 'class-validator';

export class CreateCatDto {
@IsString()
readonly name: string;

@IsInt()
readonly age: number;

@IsString()
readonly breed: string;
}
// cats.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { CreateCatDto } from './create-cat.dto';

@Controller('cats')
export class CatsController {
@Post()
create(@Body() createCatDto: CreateCatDto): string {
return `This endpoint creates a new cat with data: ${JSON.stringify(createCatDto)}`;
}
}

In this example, we define a data transfer object (DTO) CreateCatDto using class-validator for validating request payloads.

Conclusion

Controllers are a fundamental building block of NestJS applications, providing a structured way to handle incoming requests and generate responses. In this guide, we’ve explored basic routing, important decorators for request handling functions, redirection, and handling request payloads. Understanding these concepts will empower you to build robust and scalable applications with NestJS. Happy coding!

--

--