0
0
NestJSframework~15 mins

Status codes and headers in NestJS - Deep Dive

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