0
0
NestJSframework~5 mins

Response handling in NestJS

Choose your learning style9 modes available
Introduction

Response handling lets your server send back clear and useful answers to users or other programs. It helps show the right data or messages after someone asks for something.

When you want to send data back after a user asks for information.
When you need to send a success or error message after a user sends data.
When you want to control the status code and headers of the reply.
When you want to format the response in JSON or other formats.
When you want to add custom headers or cookies to the response.
Syntax
NestJS
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller('example')
export class ExampleController {
  @Get()
  getExample(@Res() res: Response) {
    res.status(200).json({ message: 'Hello World' });
  }
}

Use @Res() decorator to get the raw response object from Express.

Call methods like status() and json() on the response to send data.

Examples
Sends a plain text response with status 200.
NestJS
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller('hello')
export class HelloController {
  @Get()
  sayHello(@Res() res: Response) {
    res.status(200).send('Hello NestJS');
  }
}
Sends a JSON response with status 201.
NestJS
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller('json')
export class JsonController {
  @Get()
  sendJson(@Res() res: Response) {
    res.status(201).json({ success: true, data: [1, 2, 3] });
  }
}
Returns data directly without using @Res(). NestJS handles the response automatically.
NestJS
import { Controller, Get } from '@nestjs/common';

@Controller('simple')
export class SimpleController {
  @Get()
  getSimple() {
    return { message: 'Auto handled response' };
  }
}
Sample Program

This controller sends a JSON greeting message with status code 200 when you visit the '/greet' route.

NestJS
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller('greet')
export class GreetController {
  @Get()
  greetUser(@Res() res: Response) {
    const greeting = { message: 'Welcome to NestJS!' };
    res.status(200).json(greeting);
  }
}
OutputSuccess
Important Notes

Using @Res() means you must handle sending the response yourself.

If you return data directly without @Res(), NestJS sends the response automatically.

Always set the correct status code to help clients understand the result.

Summary

Response handling controls what your server sends back to users or clients.

You can use @Res() to customize the response fully or return data directly for automatic handling.

Setting status codes and response formats clearly improves communication with clients.