Status Codes and Responses

Default Codes and @HttpCode

By default NestJS returns 200 for every method except POST, which returns 201. Change it with @HttpCode(). Throw a built-in exception for errors.

import { Controller, Delete, Get, Header, HttpCode, HttpStatus, NotFoundException, Param, ParseIntPipe, Post, Redirect } from '@nestjs/common';

@Controller('products')
export class ProductsController {
  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)            // 204, no body
  remove(@Param('id', ParseIntPipe) id: number) {}

  @Post('search')
  @HttpCode(HttpStatus.OK)                    // a POST that only reads data
  search() { return []; }

  @Get(':id')
  @Header('Cache-Control', 'public, max-age=60')
  findOne(@Param('id', ParseIntPipe) id: number) {
    if (id > 100) throw new NotFoundException(`Product ${id} not found`);
    return { id };
  }

  @Get('old-catalog')
  @Redirect('/products', 301)
  oldCatalog() {}
}

What the Client Sees

Example

curl -i -X DELETE http://localhost:3000/products/7
curl -i http://localhost:3000/products/500

Example output

HTTP/1.1 204 No Content

HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8

{"message":"Product 500 not found","error":"Not Found","statusCode":404}

Tip: Async handlers are fine: return a Promise (or an RxJS Observable) and NestJS waits for it before sending the response.