0
0
NestJSframework~5 mins

Status codes and headers in NestJS

Choose your learning style9 modes available
Introduction

Status codes and headers tell the browser or client what happened with the request and provide extra information.

When you want to tell the client if a request was successful or if there was an error.
When you need to send extra information like content type or caching rules.
When you want to redirect the user to another page.
When you want to control how browsers handle your response.
When you want to customize the response for APIs or web pages.
Syntax
NestJS
import { Controller, Get, Res, HttpStatus } from '@nestjs/common';
import { Response } from 'express';

@Controller('example')
export class ExampleController {
  @Get()
  exampleMethod(@Res() res: Response) {
    res.status(HttpStatus.OK).set('Custom-Header', 'value').send('Hello');
  }
}

Use @Res() to get the response object and control status and headers.

HttpStatus provides easy-to-read status code names.

Examples
Sends a 200 OK status with a simple message.
NestJS
res.status(200).send('OK');
Sends a 404 Not Found status using the HttpStatus enum.
NestJS
res.status(HttpStatus.NOT_FOUND).send('Not Found');
Adds a custom header before sending the response.
NestJS
res.set('X-Custom-Header', '123').send('With header');
Redirects the client to a new URL with status 302.
NestJS
res.status(302).set('Location', '/new-url').send();
Sample Program

This controller has three routes:

  • /status/success sends a 200 status with a custom header and message.
  • /status/error sends a 400 status with an error header and message.
  • /status/redirect sends a 302 redirect to the success route.
NestJS
import { Controller, Get, Res, HttpStatus } from '@nestjs/common';
import { Response } from 'express';

@Controller('status')
export class StatusController {
  @Get('success')
  success(@Res() res: Response) {
    res.status(HttpStatus.OK).set('X-Message', 'Success').send('Request succeeded');
  }

  @Get('error')
  error(@Res() res: Response) {
    res.status(HttpStatus.BAD_REQUEST).set('X-Error', 'Invalid data').send('Bad request');
  }

  @Get('redirect')
  redirect(@Res() res: Response) {
    res.status(HttpStatus.FOUND).set('Location', '/status/success').send();
  }
}
OutputSuccess
Important Notes

Using @Res() means you handle the response fully; NestJS won't send it automatically.

Always set status before sending the response.

Headers must be set before sending the body.

Summary

Status codes tell the client what happened with the request.

Headers provide extra information about the response.

In NestJS, use @Res() with Express response to set status and headers.