# Understanding HTTP Status Codes and Headers in NestJS

When building APIs with **NestJS**, one of the crucial aspects is handling HTTP status codes and headers in your responses.

These elements provide valuable information to clients about the outcome of their requests and help shape the behavior of the communication between the server and the client.

## HTTP Status Codes

HTTP status codes are three-digit numbers returned by the server to indicate the status of the request made by the client. NestJS makes it straightforward to set these codes in your API responses.

## Setting HTTP Status Codes

In NestJS, you can set the HTTP status code using the `@HttpCode` decorator or by directly chaining it with the response. Let's look at an example:

Create a new controller. I created one with the name of `response` with the help of this:

```javascript
nest g controller response
```

```javascript
import { Controller, Get, HttpCode } from '@nestjs/common';

@Controller('response')
export class ResponseController {
  @Get()
  @HttpCode(201)
  findAll() {
    return 'Shameel is testing 201 response with GET request.';
  }
}
```

By default, a GET request is sent with a 200 status code.  
In this example, the `@HttpCode(201)` decorator explicitly sets the HTTP status code to 201 OK.

When you test it with POSTMAN (or any other tool), you should be able to verify it.

![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0y0k0urtrrdiln85tzi.png (800×361)](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb0y0k0urtrrdiln85tzi.png align="left")

## Common HTTP Status Codes

Here are a few common HTTP status codes and their meanings:

* **200 OK:** The request was successful.
    
* **201 Created:** The request was successful, and a new resource was created.
    
* **400 Bad Request:** The server could not understand the request.
    
* **404 Not Found:** The requested resource could not be found.
    

Ensure to choose the appropriate status code based on the semantics of your API.

### Using HttpStatus Enum

`HttpStatus` is an Enum in which you can use proper string names; this way, you won't have to memorize status codes for the particular type of action that you are going to do.

All you have to do is [impo](https://www.typescriptlang.org/docs/handbook/enums.html)rt `HttpStatus` from `@nestjs/common` and then use it like this:

![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/icm4bui5z093c8sj6c2s.png (700×256)](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ficm4bui5z093c8sj6c2s.png align="left")

If you hover over `CREATED` then you can see its actual value. That should be the case with any of the Enum and its string you use in TypeScript.

**Code Snippet:**

```javascript
import { Controller, Get, HttpCode, HttpStatus } from '@nestjs/common';

@Controller('response')
export class ResponseController {
  @Get()
  @HttpCode(HttpStatus.CREATED)
  findAll() {
    return 'Shameel is testing 201 response with GET request.';
  }
}
```

## HTTP Headers

HTTP headers provide additional information about the server's response or the request being made. NestJS allows you to work with headers easily.

## Setting HTTP Headers

To set HTTP headers in NestJS, you can use the `@Header` decorator or directly set them using the response object. Here's an example:

```javascript
import { Controller, Get, Header, Res } from '@nestjs/common';

@Controller('example')
export class ExampleController {
  @Get()
  @Header('Cache-Control', 'no-cache') // Set header using @Header decorator
  findAll(@Res() response): string {
    return 'This is the response body';
  }
}
```

In this example, the `@Header('Cache-Control', 'no-cache')` decorator sets the Cache-Control header to `'no-cache'`.

## Common HTTP Headers

* **Content-Type:** Specifies the media type of the resource.
    
* **Cache-Control:** Directs caching mechanisms in both requests and responses.
    
* **Authorization:** Contains credentials for authenticating the client with the server.
    

Below is the code of a POST request handler:

```javascript
  @Post()
  @Header('Cache-Control', 'none')
  @Header('X-My-Header', 'Shameel')
  create() {
    return 'Shameel is POST request with additional headers.';
  }
```

You can try it with POSTMAN like this:

![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fen6ajqex2g4s5eagbfb.png (800×487)](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffen6ajqex2g4s5eagbfb.png align="left")

## Conclusion

Understanding and effectively using HTTP status codes and headers in your NestJS application is crucial for building robust and reliable APIs. Whether you're indicating the success of a request or controlling caching behaviour, mastering these concepts will enhance the communication between your server and clients.

Remember to refer to the official NestJS documentation for more in-depth information and advanced use cases.

If you’re a visual learner, check out the following video tutorial for this blog:

[https://www.youtube.com/watch?v=v7e59lQKz6U](https://www.youtube.com/watch?v=v7e59lQKz6U)

***Follow us for more such content:***

[**https://www.linkedin.com/company/hasabtech**](https://www.linkedin.com/company/hasabtech)

[https://www.youtube.com/@hasabTech](https://www.youtube.com/@hasabTech)

[https://www.instagram.com/hasab.tech/](https://www.instagram.com/hasab.tech/)

[https://www.facebook.com/hasabTech](https://www.facebook.com/hasabTech)
