Bird
Raised Fist0
NestJSframework~20 mins

Response handling in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Response Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the HTTP status code returned by this NestJS controller method?
Consider the following NestJS controller method. What HTTP status code will the client receive when this endpoint is called?
NestJS
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller('items')
export class ItemsController {
  @Get()
  getItems(@Res() res: Response) {
    res.json({ message: 'List of items' });
  }
}
A200 OK
B201 Created
C204 No Content
D500 Internal Server Error
Attempts:
2 left
💡 Hint
When you use res.json() without setting status, what is the default HTTP status code?
📝 Syntax
intermediate
2:00remaining
Which option correctly sets a custom HTTP header in a NestJS response?
You want to add a custom header 'X-Custom-Header' with value 'NestJS' to the HTTP response. Which code snippet correctly does this?
NestJS
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller('test')
export class TestController {
  @Get('header')
  setHeader(@Res() res: Response) {
    // Add custom header here
    res.send('Header set');
  }
}
Ares.append('X-Custom-Header', 'NestJS');
Bres.set('X-Custom-Header', 'NestJS');
Cres.addHeader('X-Custom-Header', 'NestJS');
Dres.header('X-Custom-Header', 'NestJS');
Attempts:
2 left
💡 Hint
Check Express response methods for setting headers.
❓ state_output
advanced
2:00remaining
What will be the JSON response body from this NestJS controller method?
Analyze the following NestJS controller method. What JSON will the client receive?
NestJS
import { Controller, Get } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get('profile')
  getProfile() {
    return { id: 1, name: 'Alice', active: true };
  }
}
A{"id":1,"name":"Alice","active":true}
B"{id:1, name:'Alice', active:true}"
C{"id":"1","name":"Alice","active":"true"}
D{"id":1,"name":"Alice"}
Attempts:
2 left
💡 Hint
What does returning a plain object from a NestJS controller method do?
🔧 Debug
advanced
2:00remaining
Why does this NestJS controller method cause a runtime error?
Examine the code below. When calling this endpoint, a runtime error occurs. What is the cause?
NestJS
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller('orders')
export class OrdersController {
  @Get('list')
  listOrders(@Res() res: Response) {
    res.json({ orders: [] });
  }
}
Ares.json() is not a function on Response object.
BMissing await keyword before res.json() causes error.
CUsing both return and res.json() causes NestJS to send response twice.
DThe method lacks a @Post decorator causing mismatch.
Attempts:
2 left
💡 Hint
Check how NestJS handles responses when @Res() is used with return statements.
🧠 Conceptual
expert
3:00remaining
Which option correctly describes how NestJS handles response serialization by default?
In NestJS, when a controller method returns a plain object, how does NestJS handle the response serialization and what can you do to customize it?
ANestJS requires you to always use @Res() and call res.json() to send JSON responses.
BNestJS sends returned objects as raw JavaScript without serialization; you must manually call JSON.stringify().
CNestJS converts returned objects to XML by default; JSON serialization requires extra setup.
DNestJS automatically serializes returned objects to JSON using class-transformer; you can customize serialization with @Exclude and @Expose decorators.
Attempts:
2 left
💡 Hint
Think about how NestJS integrates with class-transformer for response objects.

Practice

(1/5)
1. In NestJS, what is the primary purpose of using the @Res() decorator in a controller method?
easy
A. To define a route path for the controller method
B. To inject a service into the controller
C. To access and customize the HTTP response object directly
D. To automatically serialize the response data

Solution

  1. Step 1: Understand the role of @Res()

    The @Res() decorator gives direct access to the HTTP response object, allowing full control over the response.
  2. Step 2: Differentiate from other decorators

    Other decorators like @Inject() inject services, and route decorators define paths, but @Res() is specifically for response handling.
  3. Final Answer:

    To access and customize the HTTP response object directly -> Option C
  4. Quick Check:

    @Res() = direct response control [OK]
Hint: Remember: @Res() means direct response access [OK]
Common Mistakes:
  • Confusing @Res() with service injection
  • Thinking @Res() defines routes
  • Assuming @Res() auto-serializes data
2. Which of the following is the correct way to set a 201 status code and send a JSON response using @Res() in NestJS?
easy
A. res.status(201).json({ message: 'Created' });
B. res.sendStatus(201).json({ message: 'Created' });
C. res.json(201, { message: 'Created' });
D. res.statusCode(201).send({ message: 'Created' });

Solution

  1. Step 1: Recall Express response methods

    In NestJS, @Res() uses Express response methods. The correct way to set status and send JSON is res.status(201).json(...).
  2. Step 2: Identify incorrect method usage

    sendStatus sends status and ends response, so chaining .json() is invalid. res.json(201, ...) and res.statusCode(201) are not valid Express methods.
  3. Final Answer:

    res.status(201).json({ message: 'Created' }); -> Option A
  4. Quick Check:

    Set status then json = res.status(201).json(...) [OK]
Hint: Use res.status(code).json(data) to set status and send JSON [OK]
Common Mistakes:
  • Using sendStatus then chaining json
  • Passing status code as first json argument
  • Using non-existent statusCode method
3. Given the following NestJS controller method, what will be the HTTP status code and response body sent to the client?
async getData(@Res() res) {
  const data = { id: 1, name: 'NestJS' };
  return res.status(202).json(data);
}
medium
A. Status 202 with body { id: 1, name: 'NestJS' }
B. Status 200 with body { id: 1, name: 'NestJS' }
C. Status 202 with empty body
D. Status 500 with error message

Solution

  1. Step 1: Analyze response status setting

    The method calls res.status(202), so the HTTP status code will be 202 (Accepted).
  2. 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.
  3. Final Answer:

    Status 202 with body { id: 1, name: 'NestJS' } -> Option A
  4. Quick Check:

    Status 202 + JSON data = Status 202 with body { id: 1, name: 'NestJS' } [OK]
Hint: res.status(code).json(data) sets status and sends data [OK]
Common Mistakes:
  • Assuming default 200 status instead of 202
  • Thinking body is empty when using json()
  • Confusing status codes with error codes
4. Identify the error in the following NestJS controller method that uses @Res():
async sendResponse(@Res() res) {
  res.json({ message: 'Hello' });
  res.status(200);
}
medium
A. res.status must be called before returning from method
B. Missing await keyword before res.json
C. res.json should be replaced with res.sendStatus
D. Calling res.status after res.json causes no effect

Solution

  1. Step 1: Understand Express response flow

    Calling res.json() sends the response immediately and ends it.
  2. Step 2: Analyze order of method calls

    Calling res.status(200) after res.json() has no effect because response is already sent.
  3. Final Answer:

    Calling res.status after res.json causes no effect -> Option D
  4. Quick Check:

    Set status before sending response [OK]
Hint: Always set status before sending response [OK]
Common Mistakes:
  • Calling res.status after res.json
  • Thinking res.json needs await
  • Confusing res.sendStatus with res.json
5. You want to create a NestJS controller method that returns a 404 status with a JSON error message if a user is not found, but returns the user data with status 200 if found. Which code snippet correctly implements this response handling?
hard
A. 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); } }
B. 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); }
C. 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); } }
D. async getUser(@Res() res, @Param('id') id: string) { const user = await this.userService.findById(id); if (!user) { res.sendStatus(404); } else { res.json(user); } }

Solution

  1. 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 calls res.status(404).json(...) and res.status(200).json(...), chaining status and JSON response properly.
  2. 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); } } 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.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.
  3. Final Answer:

    correctly sets status and sends JSON error or data -> Option B
  4. Quick Check:

    Chain status and json for correct response [OK]
Hint: Chain res.status(code).json(data) for clear responses [OK]
Common Mistakes:
  • Calling res.json before res.status
  • Using res.sendStatus without JSON body
  • Separating status and json calls without chaining
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