Route Decorators
⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 12 min
Route Decorators map HTTP methods and specific URL paths to controller methods.
Overview
While the @Controller() decorator defines the base prefix for the entire class, Route Decorators define the specific endpoints and HTTP verbs that a given method handles.
Nest provides decorators for all standard HTTP methods, allowing you to easily build comprehensive REST APIs.
Key Concepts
- HTTP Verbs:
@Get(),@Post(),@Put(),@Patch(),@Delete(),@Options(),@Head(), and@All(). - Path Mapping: You can pass a string to the decorator to append a specific path to the controller’s prefix (e.g.,
@Get('active')). - Status Codes: By default, Nest handles status codes automatically (200 for everything except POST which is 201). You can override this with
@HttpCode(). - Headers: You can specify custom response headers using the
@Header()decorator.
Code Examples
Standard HTTP Methods
@Controller('users')
export class UsersController {
// GET /users
@Get()
findAll() {}
// POST /users
@Post()
create() {}
// GET /users/active
@Get('active')
findActiveUsers() {}
// DELETE /users
@Delete()
deleteAll() {}
}
Custom Status Codes and Headers
You can easily override the default behavior using additional decorators on the method.
import { Controller, Post, HttpCode, HttpStatus, Header } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Post()
// Change the default 201 to 204 No Content
@HttpCode(HttpStatus.NO_CONTENT)
// Add a custom response header
@Header('Cache-Control', 'none')
create() {
return 'This action adds a new user';
}
}
The @All() Decorator
If you need a method to handle all HTTP verbs for a specific path, use @All().
// Handles GET, POST, PUT, DELETE, etc. to /webhook
@All('webhook')
handleIncomingWebhook() {
return 'Handled';
}
Best Practices
- Use
HttpStatusEnum: Instead of using magic numbers like@HttpCode(204), use Nest’s built-inHttpStatus.NO_CONTENTenum for better readability. - Understand
PutvsPatch: Use@Put()for full resource replacements, and@Patch()for partial updates. - Keep Paths Consistent: Don’t put trailing or leading slashes in your route decorator strings (e.g., use
@Get('profile')instead of@Get('/profile/')). Nest handles slashes automatically.