Bird
Raised Fist0
NestJSframework~15 mins

Status codes and headers in NestJS - Deep Dive

Choose your learning style10 modes available
Overview - Status codes and headers
What is it?
Status codes and headers are parts of the response a server sends back to a client in web applications. Status codes are numbers that tell the client if the request was successful or if there was an error. Headers are extra pieces of information sent along with the response, like instructions or details about the data. Together, they help the client understand how to handle the response.
Why it matters
Without status codes and headers, clients would not know if their requests worked or failed, or how to process the data they receive. This would make web communication confusing and unreliable. Status codes and headers create a clear, standardized way for servers and clients to talk, making web apps work smoothly and predictably.
Where it fits
Before learning status codes and headers, you should understand basic HTTP requests and responses. After this, you can learn about middleware and advanced response handling in NestJS, like interceptors and exception filters, which use status codes and headers to control app behavior.
Mental Model
Core Idea
Status codes tell the story of the request's result, and headers add important details to guide how the client uses the response.
Think of it like...
Imagine sending a letter: the status code is like the postmark showing if it was delivered or returned, and headers are like notes on the envelope telling the receiver how to open or handle the letter.
┌───────────────┐
│ HTTP Response │
├───────────────┤
│ Status Code   │ ← tells success or error
│ Headers       │ ← extra info about response
│ Body          │ ← actual data sent
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding HTTP Status Codes Basics
🤔
Concept: Status codes are three-digit numbers that indicate the result of an HTTP request.
HTTP status codes are grouped by their first digit: 1xx means informational, 2xx means success, 3xx means redirection, 4xx means client error, and 5xx means server error. For example, 200 means OK, 404 means Not Found, and 500 means Internal Server Error.
Result
You can recognize what happened with a request just by looking at its status code.
Knowing status codes helps you quickly understand if a request succeeded or failed without reading the full response.
2
FoundationRole of HTTP Headers in Responses
🤔
Concept: Headers are key-value pairs sent with the response to provide extra information about the data or instructions for the client.
Common headers include Content-Type (tells the data format), Cache-Control (tells if data can be saved), and Set-Cookie (sends cookies). Headers help clients know how to handle the response body properly.
Result
You understand how servers communicate extra details beyond just the data.
Headers are essential for controlling client behavior and ensuring data is interpreted correctly.
3
IntermediateSetting Status Codes in NestJS Controllers
🤔Before reading on: do you think NestJS sets status codes automatically or do you always have to set them manually? Commit to your answer.
Concept: NestJS allows you to set status codes explicitly or rely on defaults for common responses.
In NestJS, you can use decorators like @HttpCode() to set a status code on a controller method. For example, @HttpCode(201) sets the status to Created. If you return a value without setting a code, NestJS defaults to 200 for GET and 201 for POST.
Result
You can control the exact status code sent to clients from your API endpoints.
Understanding how to set status codes explicitly prevents confusion and ensures clients get the right signals about request results.
4
IntermediateAdding Custom Headers in NestJS Responses
🤔Before reading on: do you think headers can only be set globally or can they be set per response in NestJS? Commit to your answer.
Concept: NestJS lets you add headers to individual responses using the response object or decorators.
You can inject the response object from Express or Fastify using @Res() and call res.setHeader('X-Custom-Header', 'value'). Alternatively, use @Header('X-Custom-Header', 'value') decorator on controller methods to add headers declaratively.
Result
Your API can send extra information or instructions to clients on a per-response basis.
Knowing how to add headers per response allows flexible control over client-server communication.
5
IntermediateCommon Status Codes and Their Meanings
🤔Before reading on: do you think 204 No Content responses include a body or not? Commit to your answer.
Concept: Certain status codes have special meanings and rules about response bodies.
204 means No Content and should not include a response body. 400 means Bad Request, indicating client error. 401 means Unauthorized, 403 means Forbidden, and 404 means Not Found. 500 means server error. Knowing these helps you design APIs that communicate clearly.
Result
You can choose the right status code to match the situation and client expectations.
Using correct status codes improves API clarity and helps clients handle responses properly.
6
AdvancedUsing Interceptors to Modify Status and Headers
🤔Before reading on: do you think interceptors can change status codes and headers after controller logic runs? Commit to your answer.
Concept: Interceptors in NestJS can modify responses globally or per route, including status codes and headers.
Interceptors wrap around controller methods. You can use them to add headers or change status codes dynamically based on logic. For example, an interceptor can add security headers or transform error codes before sending the response.
Result
You gain powerful control over responses beyond controller methods.
Understanding interceptors unlocks advanced response customization and cross-cutting concerns handling.
7
ExpertHow NestJS Integrates Status and Headers with Platform Adapters
🤔Before reading on: do you think NestJS handles status codes and headers itself or delegates to underlying HTTP platforms? Commit to your answer.
Concept: NestJS uses platform adapters (like Express or Fastify) to handle low-level HTTP details including status codes and headers.
When you set status codes or headers in NestJS, it calls methods on the underlying platform's response object. This means behavior can slightly differ depending on the adapter. NestJS abstracts this but understanding the delegation helps debug issues and optimize performance.
Result
You know where status codes and headers are actually set and how NestJS fits in the HTTP stack.
Knowing the adapter layer clarifies why some header or status code behaviors differ and how to handle platform-specific quirks.
Under the Hood
When a NestJS controller returns a response, the framework translates the returned value into an HTTP response. Status codes and headers are set on the underlying platform's response object (like Express's res). NestJS provides decorators and methods to modify these before the response is sent. The platform then serializes headers and status codes into the actual HTTP response sent over the network.
Why designed this way?
NestJS was designed to be platform-agnostic, so it delegates HTTP details to adapters like Express or Fastify. This separation allows NestJS to focus on application logic and keep HTTP handling flexible. It also lets developers switch platforms without rewriting core logic. Using decorators and interceptors provides a declarative and modular way to control responses.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ NestJS       │──────▶│ Platform      │──────▶│ HTTP Response │
│ Controller   │       │ Adapter (e.g.,│       │ Sent to Client│
│ Logic        │       │ Express)      │       │               │
└───────────────┘       └───────────────┘       └───────────────┘
       ▲                      ▲
       │                      │
  Decorators &           Status codes &
  Interceptors           Headers set here
Myth Busters - 4 Common Misconceptions
Quick: Do you think a 200 status code always means the response body contains data? Commit to yes or no.
Common Belief:A 200 status code means the response always has data.
Tap to reveal reality
Reality:A 200 status code means the request succeeded, but the body can be empty or contain metadata only.
Why it matters:Assuming 200 always means data can cause client errors when they expect content that isn't there.
Quick: Do you think headers can be set after the response body is sent? Commit to yes or no.
Common Belief:Headers can be added or changed anytime before or after sending the response body.
Tap to reveal reality
Reality:Headers must be set before the response body is sent; after sending, headers are locked and cannot be changed.
Why it matters:Trying to set headers too late causes runtime errors or missing headers, breaking client expectations.
Quick: Do you think NestJS automatically sets all headers for you without any developer input? Commit to yes or no.
Common Belief:NestJS handles all headers automatically, so developers don't need to set them.
Tap to reveal reality
Reality:NestJS sets some default headers but developers must set custom or specific headers explicitly.
Why it matters:Relying on defaults can cause missing important headers like CORS or security headers, leading to bugs or vulnerabilities.
Quick: Do you think status codes are the same across all HTTP platforms NestJS supports? Commit to yes or no.
Common Belief:Status codes behave identically regardless of the underlying HTTP platform.
Tap to reveal reality
Reality:Some platforms handle certain status codes or headers differently, causing subtle behavior changes.
Why it matters:Ignoring platform differences can cause unexpected bugs or inconsistent API behavior.
Expert Zone
1
Some status codes like 204 No Content require no response body, and sending one can cause client errors.
2
Headers like Set-Cookie must be handled carefully to avoid security issues like session hijacking.
3
Interceptors can override status codes set in controllers, which can cause confusion if not documented.
When NOT to use
Avoid manually setting status codes and headers in simple CRUD endpoints where defaults suffice; use NestJS built-in decorators instead. For complex response manipulation, consider using interceptors or middleware. If you need very low-level control, directly use the platform adapter's response object.
Production Patterns
In production, APIs use status codes consistently to signal errors and successes, often with global exception filters setting error codes. Security headers like Content-Security-Policy are added globally via middleware or interceptors. Custom headers are used for tracing requests or feature flags. Interceptors handle response transformations and header additions centrally.
Connections
HTTP Protocol
Status codes and headers are fundamental parts of the HTTP protocol that NestJS builds upon.
Understanding HTTP basics helps grasp why status codes and headers exist and how they control web communication.
Middleware in Web Frameworks
Middleware often manipulates headers and status codes before or after controller logic.
Knowing how middleware works clarifies how headers and status codes can be set or overridden globally.
Postal Mail System
Both use standardized signals (postmarks/status codes) and instructions (envelope notes/headers) to communicate delivery status and handling.
Recognizing this similarity helps understand the purpose of status codes and headers as communication tools.
Common Pitfalls
#1Setting headers after sending the response body causes errors.
Wrong approach:res.send('data'); res.setHeader('X-Test', 'value');
Correct approach:res.setHeader('X-Test', 'value'); res.send('data');
Root cause:Headers must be sent before the body; setting them after is too late.
#2Returning a 204 No Content status with a response body.
Wrong approach:@HttpCode(204) @Get() getData() { return { message: 'Hello' }; }
Correct approach:@HttpCode(204) @Get() getData() { return null; }
Root cause:204 status means no body; sending one violates HTTP rules and confuses clients.
#3Not setting Content-Type header for JSON responses.
Wrong approach:return { name: 'NestJS' }; // no Content-Type header set explicitly
Correct approach:@Header('Content-Type', 'application/json') return { name: 'NestJS' };
Root cause:Without Content-Type, clients may not parse response correctly.
Key Takeaways
Status codes are three-digit numbers that tell clients if a request succeeded or failed and why.
Headers provide extra information about the response, guiding clients on how to handle the data.
In NestJS, you can set status codes and headers using decorators, response objects, or interceptors for flexible control.
Headers must be set before sending the response body, and some status codes have special rules about response content.
Understanding how NestJS delegates HTTP details to platform adapters helps debug and optimize response handling.

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