Default Is 200/201 — Override With @HttpCode
HTTP Status Codes
Nest sets sensible default status codes based on the HTTP verb. Override them with `@HttpCode` when you need to.
What you'll learn
- Know the default status code per verb
- Set custom status codes with `@HttpCode`
- Use the `HttpStatus` enum for readability
By default, Nest picks a sensible HTTP status for you based on the verb:
200 for reads, 201 for creates. When that’s wrong, @HttpCode
overrides it in one line.
Defaults By Verb
| Decorator | Default status |
|---|---|
@Get | 200 OK |
@Post | 201 Created |
@Put | 200 OK |
@Patch | 200 OK |
@Delete | 200 OK |
@Head | 200 OK (no body) |
Those defaults match what most REST APIs do. The only one that surprises
people is @Post defaulting to 201 — that’s why an idempotent action
(“login”, “search”) on POST often wants an override.
Override With @HttpCode
import { Controller, Post, Delete, HttpCode } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Post('login')
@HttpCode(200) // login isn't really a "create"
login() {
return { token: '…' };
}
@Delete(':id')
@HttpCode(204) // 204 No Content for hard deletes
remove() {
return; // body is ignored at 204
}
} Use the HttpStatus Enum
Magic numbers are fine for ones everyone knows (200, 404, 500), but for
anything else HttpStatus makes intent obvious:
import { HttpCode, HttpStatus } from '@nestjs/common';
@Post('verify')
@HttpCode(HttpStatus.ACCEPTED) // 202
verify() { /* … */ } You can also use it when throwing exceptions:
import { HttpException, HttpStatus } from '@nestjs/common';
throw new HttpException('Too many', HttpStatus.TOO_MANY_REQUESTS); When to Reach for Built-In Exceptions
For common errors, Nest ships pre-baked classes that set the status for
you — BadRequestException (400), UnauthorizedException (401),
ForbiddenException (403), NotFoundException (404),
ConflictException (409), InternalServerErrorException (500).
import { NotFoundException } from '@nestjs/common';
@Get(':id')
findOne(@Param('id') id: string) {
const user = this.users.find(id);
if (!user) throw new NotFoundException(`User ${id} not found`);
return user;
} That throws a structured 404 with a JSON body — no manual res.status()
gymnastics.