Performance: Response handling
Response handling affects how quickly the server sends data back to the client, impacting page load speed and interaction responsiveness.
async getData() { const data = await this.service.fetchData(); return data; // Let NestJS handle JSON serialization }
async getData() { const data = await this.service.fetchData(); return JSON.stringify(data); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual JSON.stringify in response | 0 | 0 | 0 | [X] Bad |
| Returning object for NestJS to serialize | 0 | 0 | 0 | [OK] Good |
| Loading full file buffer before sending | 0 | 0 | 0 | [X] Bad |
| Streaming file response | 0 | 0 | 0 | [OK] Good |
| Manual header setting in method | 0 | 0 | 0 | [X] Bad |
| Using @Header decorators | 0 | 0 | 0 | [OK] Good |
@Res() decorator in a controller method?@Res()@Res() decorator gives direct access to the HTTP response object, allowing full control over the response.@Inject() inject services, and route decorators define paths, but @Res() is specifically for response handling.@Res() = direct response control [OK]@Res() in NestJS?@Res() uses Express response methods. The correct way to set status and send JSON is res.status(201).json(...).sendStatus sends status and ends response, so chaining .json() is invalid. res.json(201, ...) and res.statusCode(201) are not valid Express methods.async getData(@Res() res) {
const data = { id: 1, name: 'NestJS' };
return res.status(202).json(data);
}res.status(202), so the HTTP status code will be 202 (Accepted).{ id: 1, name: 'NestJS' } with .json(data), so the body will contain this object.@Res():async sendResponse(@Res() res) {
res.json({ message: 'Hello' });
res.status(200);
}res.json() sends the response immediately and ends it.res.status(200) after res.json() has no effect because response is already sent.res.status(404).json(...) and res.status(200).json(...), chaining status and JSON response properly.res.json() before res.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);
}
} calls res.json() before res.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);
}
} uses res.sendStatus(404) which sends response immediately but does not send JSON error message.Pass the test and this pattern moves unknown