Sling Academy
Home/Node.js/NestJS: How to Set Custom Status Code for Response

NestJS: How to Set Custom Status Code for Response

Last updated: January 01, 2024

Overview

Understanding how to manipulate response status codes in NestJS can be crucial for creating an informative API. This tutorial shows how to set custom status codes across various situations in your NestJS application.

Basic Response Override

Setting a custom status code in NestJS can be done simply by importing and using the @HttpCode() decorator.

import { Controller, Post, HttpCode } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Post()
  @HttpCode(204)
  create() {
    return 'This action adds a new cat.';
  }
}

This will override the default status code (201 for POST requests) to 204, indicating that the request was successful but there’s no content to be sent back as a response.

Using status() Within a Service

Sometimes, setting a static status code is not sufficient, and you may need to set it dynamically. This can be done by injecting the Response object into your service.

import { Injectable, Req, Res } from '@nestjs/common';
import { Response } from 'express';

@Injectable()
export class CatsService {
  createCat(@Req() request: Request, @Res() response: Response) {
    // Your logic here
    response.status(202).send('Cat is being created.');
  }
}

This allows you to set any status code depending on your application logic.

Exception Filters for Error Handling

Setting custom error status codes is often achieved using exception filters. You can create your own Exception that extends HttpException.

import { HttpException, HttpStatus } from '@nestjs/common';

export class CatNotFoundException extends HttpException {
  constructor() {
    super('Cat not found', HttpStatus.NOT_FOUND);
  }
}

To throw this exception use:

import { Injectable } from '@nestjs/common';

@Injectable()
export class CatsService {
  findCat(catId: string) {
    // Logic to find the cat
    throw new CatNotFoundException();
  }
}

Advanced HTTP Response with ApiResponse Decorator

The @ApiResponse decorator from the @nestjs/swagger package allows fine-grained control over response status code and Swagger documentation.

import { Controller, Post, Body } from '@nestjs/common';
import { ApiResponse, ApiOperation } from '@nestjs/swagger';

@Controller('cats')
export class CatsController {
  @Post()
  @ApiOperation({ summary: 'Create cat' })
  @ApiResponse({ status: 201, description: 'The record has been successfully created.'})
  @ApiResponse({ status: 403, description: 'Forbidden.'})
  create(@Body() createCatDto: CreateCatDto) {
    // Your logic here
    return this.catsService.create(catDto);
  }
}

This approach not only handles response statuses but also assists with API documentation generation.

Conclusion

Setting custom status codes in NestJS allows better communication with front-end developers and clients who consume your API. Through decorators, response objects, and exception filters, NestJS offers versatile methods to manage status codes effectively. The chosen method depends on the use case, but a wise combination supports a robust and maintainable code architecture.

Next Article: How to Handle CORS in NestJS

Previous Article: NestJS: How to Send Custom Headers with Response

Series: Nest.js Tutorials: From Basics to Advanced

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates