How to Use @Post Decorator in NestJS: Simple Guide
In NestJS, use the
@Post decorator to define a route handler for HTTP POST requests inside a controller class. It marks a method to respond when a client sends a POST request to the specified path. You can optionally provide a route path inside @Post('path') to customize the endpoint.Syntax
The @Post decorator is used above a controller method to handle HTTP POST requests. You can use it with or without a route path.
@Post(): Handles POST requests to the controller's base route.@Post('custom-path'): Handles POST requests to the controller's base route plus/custom-path.
The method below the decorator will execute when a matching POST request is received.
typescript
import { Controller, Post } from '@nestjs/common'; @Controller('items') export class ItemsController { @Post() createItem() { // logic to create an item } @Post('special') createSpecialItem() { // logic for special item } }
Example
This example shows a simple NestJS controller with a @Post method that accepts data and returns a confirmation message. It demonstrates how to handle POST requests at the base route.
typescript
import { Controller, Post, Body } from '@nestjs/common'; @Controller('products') export class ProductsController { @Post() createProduct(@Body() productData: { name: string; price: number }) { return { message: `Product '${productData.name}' created with price $${productData.price}`, }; } }
Output
{"message":"Product 'Book' created with price $15"}
Common Pitfalls
Common mistakes when using @Post include:
- Forgetting to add
@Body()to access POST request data, resulting in undefined input. - Not specifying a route path when multiple POST handlers exist, causing route conflicts.
- Using
@Postoutside a controller class, which will not work.
Always ensure your method parameters match the expected decorators and your controller is properly registered.
typescript
import { Controller, Post, Body } from '@nestjs/common'; @Controller('users') export class UsersController { // Wrong: missing @Body() decorator @Post() createUser(userData: any) { return userData; // userData will be undefined } // Correct usage @Post('register') registerUser(@Body() userData: any) { return userData; // userData contains POST body } }
Quick Reference
Summary tips for using @Post in NestJS:
- Use
@Post()to handle POST requests at the controller's base path. - Add a string inside
@Post('path')to handle POST requests at a sub-route. - Use
@Body()to access the POST request body data. - Ensure your controller is decorated with
@Controller()and registered in a module.
Key Takeaways
Use @Post decorator above controller methods to handle HTTP POST requests.
Optionally provide a route path inside @Post('path') to customize the endpoint.
Use @Body() to access data sent in the POST request body.
Always define @Post methods inside classes decorated with @Controller.
Avoid route conflicts by specifying unique paths for multiple POST handlers.