Bird
Raised Fist0
NestJSframework~5 mins

Status codes and headers in NestJS

Choose your learning style10 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.

Practice

(1/5)
1. In NestJS, what does the HTTP status code 201 usually indicate in a response?
easy
A. A new resource was successfully created
B. The request was malformed or invalid
C. The requested resource was not found
D. The server encountered an internal error

Solution

  1. Step 1: Understand HTTP status codes

    HTTP status codes communicate the result of a client's request. Code 201 means "Created".
  2. Step 2: Match 201 with its meaning

    201 specifically means a new resource was successfully created on the server.
  3. Final Answer:

    A new resource was successfully created -> Option A
  4. Quick Check:

    201 = Created [OK]
Hint: 201 means resource created successfully [OK]
Common Mistakes:
  • Confusing 201 with 404 (not found)
  • Thinking 201 means server error
  • Mixing 201 with 400 (bad request)
2. Which of the following is the correct way to set a custom header X-Custom-Header with value 123 in a NestJS controller using Express response?
easy
A. res.setHeader('X-Custom-Header', 789);
B. res.set('X-Custom-Header', '123');
C. res.header('X-Custom-Header', '789');
D. res.addHeader('X-Custom-Header', '123');

Solution

  1. Step 1: Recall Express response methods

    Express response object uses res.set() to set headers.
  2. Step 2: Check method and value types

    res.set() accepts header name and string value. res.set('X-Custom-Header', '123'); uses correct method and string value.
  3. Final Answer:

    res.set('X-Custom-Header', '123'); -> Option B
  4. Quick Check:

    Use res.set() to set headers [OK]
Hint: Use res.set() to set headers in NestJS [OK]
Common Mistakes:
  • Using res.setHeader (not Express method)
  • Passing number instead of string as header value
  • Using non-existent res.addHeader method
3. What will be the HTTP status code and header in the response when this NestJS controller method runs?
async getData(@Res() res) {
  res.status(204).set('X-Info', 'No Content').send();
}
medium
A. Status 204 with no headers
B. Status 200 with header X-Info: No Content
C. Status 204 with header X-Info: No Content
D. Status 404 with header X-Info: No Content

Solution

  1. Step 1: Analyze status and header setting

    The code sets status to 204 and header 'X-Info' to 'No Content'.
  2. Step 2: Understand 204 status behavior

    Status 204 means "No Content" and allows custom headers. The header is set correctly.
  3. Final Answer:

    Status 204 with header X-Info: No Content -> Option C
  4. Quick Check:

    Status 204 + header set = Status 204 with header X-Info: No Content [OK]
Hint: res.status(204).set() sets status and headers [OK]
Common Mistakes:
  • Assuming 204 means no headers allowed
  • Confusing default status 200 with explicit 204
  • Ignoring header set after status
4. Identify the error in this NestJS controller method that tries to set status and headers:
async update(@Res() res) {
  res.status(200);
  res.set('Content-Type', 'application/json');
  res.send({ success: true });
  res.status(201);
}
medium
A. Calling res.status(201) after res.send() has no effect
B. res.set() must be called before res.status()
C. res.send() cannot send JSON objects
D. res.status() cannot be called twice

Solution

  1. Step 1: Review response flow

    res.send() sends the response and ends it. Any code after it won't affect response.
  2. Step 2: Check status calls order

    Calling res.status(201) after res.send() does nothing because response is already sent.
  3. Final Answer:

    Calling res.status(201) after res.send() has no effect -> Option A
  4. Quick Check:

    res.send() ends response, later status calls ignored [OK]
Hint: Set status before res.send(), not after [OK]
Common Mistakes:
  • Trying to set status after sending response
  • Thinking res.send() can't send JSON
  • Believing res.set() must come before res.status()
5. You want to send a 202 Accepted status with a custom header X-Request-ID and a JSON body in NestJS. Which code snippet correctly achieves this?
hard
A. res.send({ message: 'Accepted' }).status(202).set('X-Request-ID', requestId);
B. res.set('X-Request-ID', requestId).status(202).send('Accepted');
C. res.status(202).send({ message: 'Accepted' }).set('X-Request-ID', requestId);
D. res.status(202).set('X-Request-ID', requestId).json({ message: 'Accepted' });

Solution

  1. Step 1: Order of method calls matters

    In Express, chaining status, set, and json works if status is set before sending.
  2. Step 2: Check each option's correctness

    Options A and C call send before completing status/header setup, invalid. res.set('X-Request-ID', requestId).status(202).send('Accepted'); sets header and status but uses res.send('Accepted') sending plain text instead of JSON object. res.status(202).set('X-Request-ID', requestId).json({ message: 'Accepted' }); correctly sets status, header, sends JSON.
  3. Step 3: Confirm best practice

    res.status(202).set('X-Request-ID', requestId).json({ message: 'Accepted' }); is the clearest and most common pattern: status, set header, then send JSON.
  4. Final Answer:

    res.status(202).set('X-Request-ID', requestId).json({ message: 'Accepted' }); -> Option D
  5. Quick Check:

    Status then headers then send JSON [OK]
Hint: Chain status, set, then send/json in that order [OK]
Common Mistakes:
  • Calling send before setting status or headers
  • Using send instead of json for JSON body
  • Setting headers after sending response
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard