DEV Community

Cover image for How to Handle Custom Responses and Headers in NestJS with @Res
Shameel Uddin
Shameel Uddin

Posted on

How to Handle Custom Responses and Headers in NestJS with @Res

In the previous blog, we discussed how to modify HTTP status codes and headers while sending responses to the client. In this post, we'll explore another approach: Modifying headers manually in a NestJS controller using @Res() — similar to how it's done in Express.js.

Express vs. NestJS Response Flow

NestJS, by default, handles HTTP responses for you. This means you can simply return a value from your controller, and Nest will convert it into a response, but sometimes, you might want fine-grained control, like setting custom headers or using an existing Express-style library. In such cases, you can manually handle the response.

How to Modify Headers with @Res()

We already learned how to intercept Express request in our controller so we imported a request like

import {Controller, Get, HttpCode, HttpStatus, Header, Request}from '@nestjs/common';
Enter fullscreen mode Exit fullscreen mode

we can also import a response here like with full form Request or short form Res

import {Controller, Get, HttpCode, HttpStatus, Header, Res}from '@nestjs/common';
Enter fullscreen mode Exit fullscreen mode

Similarly we also import types for this particular Response from Express

import {Response} from 'express';
Enter fullscreen mode Exit fullscreen mode

Now Create a @Get Request

Get()   
FindAll(@Res() response: Response) {
Response.status(HttpStatus.OK) .send();
}
Enter fullscreen mode Exit fullscreen mode

Understanding @Res, res, and Response

In this code

import {Controller, Get, HttpStatus, Res} from "@nestjs/common";
import { Response } from "express";

@Controller("response")
export class ResponseController {
  @Get()
  findAll(@Res() res: Response) {
    res.status(HttpStatus.OK).send();
  }
}
Enter fullscreen mode Exit fullscreen mode
  • @Res() → Decorator to inject the response object

  • response → A custom variable name (can also be res)

  • Response → Type from express for better IntelliSense and typing

So finally, we can modify our header manually and send response to our client.

Conclusion

While NestJS encourages using its built-in response handling, the @Res decorator lets you leverage Express-style syntax for fine-grained control. Use this sparingly to avoid losing Nest’s powerful features.

Note: Use manual response handling sparingly, as it bypasses features like interceptors, exception filters, and built-in decorator.

That said, stay tuned for more advanced NestJS tips!

Video explanation available here ↓

Follow me for more such content:
YouTube: https://www.youtube.com/@ShameelUddin123
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123

Top comments (0)