NestJS Controllers

hasabTechhasabTech
3 min read

NestJS, a progressive Node.js framework, has gained popularity for its modular and scalable architecture. One of its key components is the Controller, which plays a pivotal role in handling incoming requests and defining the application's routing logic. In this blog post, we will dive into the NestJS Controller and explore its routing mechanism with practical coding examples.

Understanding NestJS Controllers

Controllers in NestJS are responsible for handling incoming HTTP requests, processing them, and returning an appropriate response. They act as the bridge between the client (request) and the server (application logic). Controllers are decorated with the @Controller decorator, and they contain methods that handle specific routes.

Let's create a simple NestJS controller to illustrate the basic structure:


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

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

In this example, we've created a CatsController decorated with @Controller('cats'). The argument passed to @Controller specifies the base route for all the methods within this controller. The @Get() decorator is used to define an HTTP GET route, and the findAll method is the handler for this route.

Routing in NestJS

NestJS follows a decorator-based approach for defining routes within controllers. Decorators are special functions prefixed with @ that provide metadata to NestJS, allowing it to understand the structure of the application.

Let's extend our CatsController to include more routes and demonstrate different HTTP methods:

// cats.controller.ts

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

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

  @Get(':id')
  findOne(@Param('id') id: string): string {
    return `This action returns cat #${id}`;
  }

  @Post()
  create(): string {
    return 'This action creates a new cat';
  }

  @Put(':id')
  update(@Param('id') id: string): string {
    return `This action updates cat #${id}`;
  }

  @Delete(':id')
  remove(@Param('id') id: string): string {
    return `This action removes cat #${id}`;
  }
}

In this extended example, we've added methods for handling GET, POST, PUT, and DELETE requests. The @Get(':id') decorator defines a route with a dynamic parameter (id), and the @Param('id') decorator extracts that parameter from the request.

Organizing Controllers in Modules

NestJS encourages the use of modules to organize the application. Controllers are often associated with modules, and the @Module decorator is used for this purpose. Here's an example of how you might organize your controllers into a module:

// cats.module.ts

import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';

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

Conclusion

NestJS controllers and routing mechanisms simplify the process of handling HTTP requests in your application. By using decorators, you can easily define routes and extract parameters from incoming requests. This modular and expressive approach contributes to the overall readability and maintainability of your code.

Remember, this is just a basic overview, and NestJS offers many more features for handling authentication, validation, and other aspects of web development.

If you’re a visual learner, check out the following video tutorial for this blog:

https://www.youtube.com/watch?v=zy3wtZVe0so&embeds_referring_euri=https%3A%2F%2Fdev.to%2F&source_ve_path=MjM4NTE

Follow us for more such content:

https://www.linkedin.com/company/hasabtech

https://www.youtube.com/@hasabTech

https://www.instagram.com/hasab.tech/

https://www.facebook.com/hasabTech

1
Subscribe to my newsletter

Read articles from hasabTech directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

hasabTech
hasabTech

HasabTech is a developer-focused educational platform committed to simplifying tech learning. We share practical coding tutorials, programming guides, and tech insights to help beginners and aspiring developers build real world skills. Our mission is to make technical education accessible, clear, and community driven. We are currently building our in house products, experimenting with real world tech solutions, and sharing what we learn along the way.