How to Create Controllers in NestJS: A Comprehensive Tutorial
NestJS is a powerful, progressive Node.js framework for building efficient and scalable server-side applications. Controllers in NestJS are essential components that handle incoming requests and return responses to the client. This tutorial will guide you through the process of creating controllers in NestJS using clear examples and best practices.
Prerequisites
- Basic knowledge of JavaScript and TypeScript
- Node.js installed on your machine
- Basic understanding of RESTful APIs
- Familiarity with the NestJS framework (recommended but not mandatory)
- An existing NestJS project environment (or you can create one)
Step 1: Setting Up Your NestJS Project
If you don’t already have a project, start by installing the Nest CLI and creating a new project:
npm i -g @nestjs/cli
nest new my-nest-project
cd my-nest-project
This will initialize a new NestJS project with a default structure.
Step 2: Understanding Controllers in NestJS
Controllers are decorated with the @Controller() decorator. They are responsible for handling routes and HTTP requests.
A simple controller example looks like this:
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
Here:
@Controller('cats')maps this controller to the/catsroute.@Get()handles GET HTTP requests to the route/cats.findAll()method returns a response.
Step 3: Creating Your First Controller
Use Nest CLI to generate a controller automatically with all boilerplate codes:
nest generate controller users
This command generates a users.controller.ts file with a default controller class.
Example Users Controller
import { Controller, Get, Post, Body, Param } from '@nestjs/common';
@Controller('users')
export class UsersController {
private users = [];
@Get()
findAll() {
return this.users;
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.users.find(user => user.id === id);
}
@Post()
create(@Body() user: any) {
this.users.push(user);
return user;
}
}
Explanation:
@Get()without parameter returns the complete list of users.@Get(':id')handles dynamic routing to fetch a user by ID.@Post()creates a new user by reading the request body via@Body().
Step 4: Registering the Controller in Module
Make sure your controller is declared in a module, often in app.module.ts or a specific module file.
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
@Module({
controllers: [UsersController],
})
export class UsersModule {}
Then import UsersModule into your root module as needed.
Step 5: Running and Testing the Controller
Launch the NestJS application:
npm run start
Test your endpoints using tools like Postman (Official site) or curl commands:
curl http://localhost:3000/users
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"id":"1","name":"John Doe"}'
Troubleshooting Tips
- Controller not responding: Verify it is declared in a module’s
controllersarray. - 404 Not Found: Check the route paths and HTTP method decorators in the controller.
- Errors on @Body or @Param: Ensure you have enabled the
ValidationPipeor installed body-parser middleware correctly.
Summary Checklist
- Installed NestJS and set up project
- Created controller class with
@Controller()decorator - Used HTTP method decorators like
@Get()and@Post() - Handled request parameters and body properly with
@Param()and@Body() - Registered controller in a NestJS module
- Tested endpoints using Postman or curl
For more details on setting up NestJS, check our related tutorial How to Install NestJS Framework: A Complete Guide.
By mastering controllers in NestJS, you gain powerful control over your application’s routing and business logic separation. Happy coding!
