The Controller decorator marks a class as a controller that handles incoming requests and sends responses in a NestJS app.
0
0
Controller decorator in NestJS
Introduction
When you want to group related request handlers for a specific part of your app.
When you need to define routes that respond to HTTP requests like GET or POST.
When organizing your backend code into clear sections for different features.
When you want to separate logic for handling requests from other parts like services.
When building REST APIs or web apps that respond to user actions.
Syntax
NestJS
@Controller('route-path') export class SomeController { // handler methods here }
The string inside @Controller() sets the base route path for all handlers in the class.
If you leave it empty like @Controller(), it will handle requests at the root path.
Examples
This controller handles all routes that start with
/users.NestJS
@Controller('users') export class UsersController { // handles routes starting with /users }
This controller handles routes at the root path
/.NestJS
@Controller()
export class AppController {
// handles routes at the root path /
}Groups all product-related routes under
/products.NestJS
@Controller('products') export class ProductsController { // add methods to handle product routes }
Sample Program
This example creates a controller with the base route /hello. It has one GET handler that returns a greeting string.
NestJS
import { Controller, Get } from '@nestjs/common'; @Controller('hello') export class HelloController { @Get() sayHello() { return 'Hello, NestJS!'; } }
OutputSuccess
Important Notes
Controllers should be simple and only handle routing and request/response logic.
Use decorators like @Get(), @Post() inside controllers to define specific routes.
Controllers are automatically discovered if registered in a module.
Summary
@Controller marks a class as a request handler group in NestJS.
It sets a base path for all routes inside the class.
Use it to organize your app's routes clearly and cleanly.