0
0
NestjsHow-ToBeginner ยท 3 min read

How to Use @Controller Decorator in NestJS: Simple Guide

In NestJS, use the @Controller decorator to define a class as a controller that handles incoming HTTP requests. This decorator marks the class to group related route handlers, making your app organized and modular.
๐Ÿ“

Syntax

The @Controller decorator is placed above a class to define it as a controller. You can optionally pass a string to set a route prefix for all methods inside the class.

  • @Controller(): Marks the class as a controller.
  • Optional prefix: A string that prefixes all routes in the controller.
typescript
import { Controller, Get } from '@nestjs/common';

@Controller('prefix')
export class SampleController {
  @Get('route')
  getMethod() {
    return 'response';
  }
}
๐Ÿ’ป

Example

This example shows a simple controller with a route prefix users. It handles GET requests to /users and returns a welcome message.

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

@Controller('users')
export class UsersController {
  @Get()
  getUsers() {
    return 'Welcome to Users API';
  }
}
Output
When you send a GET request to http://localhost:3000/users, the response will be: "Welcome to Users API"
โš ๏ธ

Common Pitfalls

Common mistakes include forgetting to add the @Controller decorator, which means NestJS won't recognize the class as a controller. Another mistake is not importing the controller in the module, so routes won't be registered.

Also, avoid using the same route prefix in multiple controllers without clear purpose, as it can cause route conflicts.

typescript
/* Wrong: Missing @Controller decorator */
import { Get } from '@nestjs/common';

export class MissingController {
  @Get()
  getData() {
    return 'No controller';
  }
}

/* Right: With @Controller decorator */
import { Controller, Get } from '@nestjs/common';

@Controller('data')
export class DataController {
  @Get()
  getData() {
    return 'Controller works';
  }
}
๐Ÿ“Š

Quick Reference

  • @Controller(): Defines a controller class.
  • Route prefix: Optional string to prefix all routes.
  • Route handlers: Use decorators like @Get(), @Post() inside the controller.
  • Register controller: Add controller to module's controllers array.
โœ…

Key Takeaways

Use @Controller to mark a class as a route handler group in NestJS.
Optionally add a route prefix string to organize routes under a common path.
Always import and register your controller in the module to activate routes.
Use HTTP method decorators like @Get inside the controller to define endpoints.
Missing @Controller or module registration causes routes not to work.