Understanding HTTP Status Codes and Headers in Nest.js
When building APIs with Nest.js, 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.
Video Explanation:
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. Nest.js makes it straightforward to set these codes in your API responses.
Setting HTTP Status Codes
In Nest.js, 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:
nest g controller response
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, GET request is sent with 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.
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 import HttpStatus
from @nestjs/common
and then use it like this:
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.
Full code:
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. Nest.js allows you to work with headers easily.
Setting HTTP Headers
To set HTTP headers in Nest.js, you can use the @Header
decorator or directly set them using the response object. Here's an example:
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:
@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:
Conclusion
Understanding and effectively using HTTP status codes and headers in your Nest.js application is crucial for building robust and reliable APIs. Whether you're indicating the success of a request or controlling caching behavior, mastering these concepts will enhance the communication between your server and clients.
Remember to refer to the official Nest.js documentation for more in-depth information and advanced use cases.
Happy coding! 🚀
Follow me for more such content:
YouTube: https://www.youtube.com/@ShameelUddin123
LinkedIn: https://www.linkedin.com/in/shameeluddin/
GitHub: https://github.com/Shameel123