Bird
Raised Fist0
NestJSframework~10 mins

Status codes and headers in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Status codes and headers
Receive HTTP Request
↓
Controller handles request
↓
Set Status Code
↓
Set Headers
↓
Send Response with Body
↓
Client receives response
The server receives a request, the controller sets status code and headers, then sends the response back to the client.
Execution Sample
NestJS
import { Controller, Get, Res } from '@nestjs/common';

@Controller('example')
export class ExampleController {
  @Get()
  getExample(@Res() res) {
    res.status(201).setHeader('X-Custom-Header', 'NestJS').send('Created');
  }
}
This code sends a response with status 201 and a custom header 'X-Custom-Header'.
Execution Table
StepActionStatus CodeHeaders SetResponse BodyEffect
1Receive GET request at /exampleN/ANoneNoneStart processing request
2Controller method getExample calledN/ANoneNonePrepare response
3Set status code to 201201NoneNoneResponse status set to Created
4Set header 'X-Custom-Header' to 'NestJS'201X-Custom-Header: NestJSNoneCustom header added
5Send response body 'Created'201X-Custom-Header: NestJSCreatedResponse sent to client
6Client receives response201X-Custom-Header: NestJSCreatedRequest complete
💡 Response sent with status 201, header set, and body 'Created'
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5Final
statusCodeundefined201201201201
headers{}{}{'X-Custom-Header': 'NestJS'}{'X-Custom-Header': 'NestJS'}{'X-Custom-Header': 'NestJS'}
responseBodyundefinedundefinedundefined'Created''Created'
Key Moments - 3 Insights
Why do we set the status code before sending the response body?
The status code must be set before sending the response because once the body is sent, the response is finalized and headers or status cannot be changed. See execution_table step 3 and 5.
Can we set multiple headers before sending the response?
Yes, you can set multiple headers before sending the response. Each header is added before the send call. In the example, only one header is set at step 4, but more can be added similarly.
What happens if we try to set headers after sending the response?
Headers cannot be modified after the response is sent. Attempting to do so will have no effect or cause an error. The response is finalized at step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the status code at step 4?
A201
B200
Cundefined
D404
💡 Hint
Check the 'Status Code' column at step 4 in the execution_table.
At which step is the response body sent to the client?
AStep 4
BStep 5
CStep 3
DStep 6
💡 Hint
Look for the step where 'Response Body' changes from undefined to 'Created' in the execution_table.
If we add another header before sending, how would the headers look at step 4?
A{}
B{'Content-Type': 'text/plain'}
C{'X-Custom-Header': 'NestJS', 'Content-Type': 'text/plain'}
DHeaders cannot be changed
💡 Hint
Refer to variable_tracker headers row after step 4 and imagine adding one more header.
Concept Snapshot
In NestJS controllers, use res.status(code) to set HTTP status.
Use res.setHeader(name, value) to add headers.
Call res.send(body) last to send response.
Set status and headers before sending.
This controls how clients understand the response.
Full Transcript
In NestJS, when a controller receives a request, it prepares a response by setting a status code and headers before sending the response body. The status code tells the client if the request was successful or not, like 201 for created. Headers add extra info, like custom metadata. The response body is sent last, finalizing the response. Trying to change status or headers after sending won't work. This flow ensures clients get clear, complete responses.

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