Discover how a simple decorator can turn messy route handling into clean, organized code!
Why Controller decorator in NestJS? - Purpose & Use Cases
Imagine building a web server where you have to write code to listen to every URL path manually and then decide what to do for each request.
You have to check the URL, method, and then call the right function yourself.
This manual approach is slow and confusing.
It's easy to make mistakes like mixing up URLs or forgetting to handle some HTTP methods.
As your app grows, the code becomes messy and hard to maintain.
The Controller decorator in NestJS lets you group related routes in one place.
You just decorate a class and its methods to automatically handle requests for specific URLs and HTTP methods.
This keeps your code clean, organized, and easy to understand.
if (req.url === '/users' && req.method === 'GET') { getUsers(); } else if (req.url === '/users' && req.method === 'POST') { createUser(); }
@Controller('users') class UserController { @Get() getUsers() {} @Post() createUser() {} }
You can build scalable, readable web servers where routes are clearly grouped and easy to manage.
Think of an online store backend where all product-related routes like listing, adding, or deleting products are neatly organized in one controller class.
Manual routing is error-prone and hard to maintain.
Controller decorator groups routes in a clean, organized way.
It makes your server code easier to read and scale.