HTTP Status Codes

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.

4 min read Level 1/5 #nestjs#http#status
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

DecoratorDefault status
@Get200 OK
@Post201 Created
@Put200 OK
@Patch200 OK
@Delete200 OK
@Head200 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.

Redirects →