Discover how NestJS response handling saves you from messy, error-filled server replies!
Why Response handling in NestJS? - Purpose & Use Cases
Imagine building a web server that sends back data to users. You write code to manually set HTTP status codes, headers, and format the response body for every request.
For example, you have to write separate code to send JSON, handle errors, and set cookies each time.
Manually managing responses is tiring and error-prone. You might forget to set the right status code or send inconsistent data formats.
This leads to bugs, security issues, and a poor user experience because clients get unexpected or broken responses.
Response handling in NestJS provides a clean, consistent way to manage what your server sends back.
It lets you easily set status codes, headers, and response bodies using decorators and helper methods, so your code stays simple and reliable.
res.status(200).json({ message: 'Success' });
@Get()
getData() {
return { message: 'Success' };
}It enables you to focus on your app logic while NestJS takes care of sending correct, consistent responses to clients.
When building an API for a shopping app, response handling ensures customers always get clear success or error messages, improving their experience and trust.
Manual response code is repetitive and risky.
NestJS response handling simplifies and standardizes replies.
This leads to cleaner code and better user experiences.
Practice
@Res() decorator in a controller method?Solution
Step 1: Understand the role of
The@Res()@Res()decorator gives direct access to the HTTP response object, allowing full control over the response.Step 2: Differentiate from other decorators
Other decorators like@Inject()inject services, and route decorators define paths, but@Res()is specifically for response handling.Final Answer:
To access and customize the HTTP response object directly -> Option CQuick Check:
@Res()= direct response control [OK]
- Confusing @Res() with service injection
- Thinking @Res() defines routes
- Assuming @Res() auto-serializes data
@Res() in NestJS?Solution
Step 1: Recall Express response methods
In NestJS,@Res()uses Express response methods. The correct way to set status and send JSON isres.status(201).json(...).Step 2: Identify incorrect method usage
sendStatussends status and ends response, so chaining.json()is invalid.res.json(201, ...)andres.statusCode(201)are not valid Express methods.Final Answer:
res.status(201).json({ message: 'Created' }); -> Option AQuick Check:
Set status then json = res.status(201).json(...) [OK]
- Using sendStatus then chaining json
- Passing status code as first json argument
- Using non-existent statusCode method
async getData(@Res() res) {
const data = { id: 1, name: 'NestJS' };
return res.status(202).json(data);
}Solution
Step 1: Analyze response status setting
The method callsres.status(202), so the HTTP status code will be 202 (Accepted).Step 2: Analyze response body sent
The method sends JSON data{ id: 1, name: 'NestJS' }with.json(data), so the body will contain this object.Final Answer:
Status 202 with body { id: 1, name: 'NestJS' } -> Option AQuick Check:
Status 202 + JSON data = Status 202 with body { id: 1, name: 'NestJS' } [OK]
- Assuming default 200 status instead of 202
- Thinking body is empty when using json()
- Confusing status codes with error codes
@Res():async sendResponse(@Res() res) {
res.json({ message: 'Hello' });
res.status(200);
}Solution
Step 1: Understand Express response flow
Callingres.json()sends the response immediately and ends it.Step 2: Analyze order of method calls
Callingres.status(200)afterres.json()has no effect because response is already sent.Final Answer:
Calling res.status after res.json causes no effect -> Option DQuick Check:
Set status before sending response [OK]
- Calling res.status after res.json
- Thinking res.json needs await
- Confusing res.sendStatus with res.json
Solution
Step 1: Check correct chaining of status and json
async getUser(@Res() res, @Param('id') id: string) { const user = await this.userService.findById(id); if (!user) { return res.status(404).json({ error: 'User not found' }); } return res.status(200).json(user); } correctly callsres.status(404).json(...)andres.status(200).json(...), chaining status and JSON response properly.Step 2: Identify errors in other options
async getUser(@Res() res, @Param('id') id: string) { const user = await this.userService.findById(id); if (!user) { res.json({ error: 'User not found' }).status(404); } else { res.json(user).status(200); } } callsres.json()beforeres.status(), which does not set status correctly. async getUser(@Res() res, @Param('id') id: string) { const user = await this.userService.findById(id); if (!user) { res.json({ error: 'User not found' }); res.status(404); } else { res.json(user); res.status(200); } } callsres.json()beforeres.status(), which does not set status correctly. async getUser(@Res() res, @Param('id') id: string) { const user = await this.userService.findById(id); if (!user) { res.sendStatus(404); } else { res.json(user); } } usesres.sendStatus(404)which sends response immediately but does not send JSON error message.Final Answer:
correctly sets status and sends JSON error or data -> Option BQuick Check:
Chain status and json for correct response [OK]
- Calling res.json before res.status
- Using res.sendStatus without JSON body
- Separating status and json calls without chaining
Ready to prove it?
Pass the test and this pattern moves unknown
