How to Create Controller in NestJS: Simple Guide
In NestJS, create a controller by defining a class decorated with
@Controller() and adding route handlers with decorators like @Get(). This class handles incoming requests and returns responses in your application.Syntax
A NestJS controller is a class decorated with @Controller(). Inside, methods handle HTTP requests using decorators like @Get(), @Post(), etc. Each method corresponds to a route and returns a response.
Parts explained:
@Controller('path'): Defines the base route path for the controller.- Class: Contains route handler methods.
@Get('subpath'): Handles GET requests to/path/subpath.- Method: Returns data or response for the route.
typescript
import { Controller, Get } from '@nestjs/common'; @Controller('items') export class ItemsController { @Get() findAll() { return 'This action returns all items'; } }
Example
This example shows a simple controller named ProductsController that handles GET requests to /products and returns a list of product names.
typescript
import { Controller, Get } from '@nestjs/common'; @Controller('products') export class ProductsController { @Get() getAllProducts() { return ['Apple', 'Banana', 'Cherry']; } }
Output
["Apple", "Banana", "Cherry"]
Common Pitfalls
Common mistakes when creating controllers include:
- Forgetting to add the
@Controller()decorator, so NestJS does not recognize the class as a controller. - Not importing the controller in the module's
controllersarray, so it is not registered. - Using incorrect HTTP method decorators or missing route paths.
Example of a wrong and right way:
typescript
/* Wrong: Missing @Controller decorator */ export class WrongController { @Get() getData() { return 'No controller decorator'; } } /* Right: With @Controller decorator and registered in module */ import { Controller, Get } from '@nestjs/common'; @Controller('right') export class RightController { @Get() getData() { return 'Controller works'; } }
Quick Reference
| Decorator | Purpose |
|---|---|
| @Controller('path') | Defines a controller with base route path |
| @Get('subpath') | Handles HTTP GET requests |
| @Post('subpath') | Handles HTTP POST requests |
| @Put('subpath') | Handles HTTP PUT requests |
| @Delete('subpath') | Handles HTTP DELETE requests |
Key Takeaways
Use @Controller() to define a controller class in NestJS.
Add route handlers with decorators like @Get(), @Post() inside the controller.
Register your controller in the module's controllers array to activate it.
Each method in the controller corresponds to an HTTP route and returns a response.
Avoid missing decorators or module registration to prevent your controller from working.