Bird
Raised Fist0
NestJSframework~10 mins

Why controllers handle incoming requests in NestJS - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why controllers handle incoming requests
Client sends HTTP request
↓
NestJS Router receives request
↓
Controller matches route
↓
Controller method executes
↓
Controller processes data
↓
Controller returns response
↓
Response sent back to client
This flow shows how a controller in NestJS receives an HTTP request, processes it, and sends back a response.
Execution Sample
NestJS
import { Controller, Get } from '@nestjs/common';

@Controller('hello')
export class HelloController {
  @Get()
  sayHello() {
    return 'Hello World!';
  }
}
A simple controller that handles GET requests to '/hello' and returns a greeting.
Execution Table
StepActionInputController MethodOutput
1Client sends GET request to /hello/helloN/ARequest received by NestJS router
2Router matches route to HelloController/helloN/ARoute matched to HelloController.sayHello()
3Controller method sayHello() executesN/AsayHello()Returns 'Hello World!'
4NestJS sends response back to clientN/AN/AResponse: 'Hello World!'
💡 Request handled and response sent, flow ends.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
requestUrlundefined/hello/hello/hello
matchedControllerundefinedHelloControllerHelloControllerHelloController
responseDataundefinedundefined'Hello World!''Hello World!'
Key Moments - 2 Insights
Why does the controller method run only after the router matches the route?
Because the router first checks the URL to find the right controller. Only then does it call the controller method, as shown in execution_table step 2 and 3.
What happens if no controller matches the incoming request?
The router cannot find a matching controller, so the request is not handled and usually a 404 error is returned. This is before step 3 in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output after step 3?
ARequest received by NestJS router
B'Hello World!'
CRoute matched to HelloController.sayHello()
DResponse sent back to client
💡 Hint
Check the 'Output' column in row for step 3.
At which step does the router match the incoming request to the controller?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column describing route matching.
If the controller method returned a different string, how would the variable 'responseData' change?
AIt would change to the new returned string
BIt would stay 'Hello World!'
CIt would become undefined
DIt would cause an error
💡 Hint
See variable_tracker 'responseData' changes after step 3.
Concept Snapshot
Controllers in NestJS handle incoming HTTP requests.
They match routes to methods that process requests.
Controllers return responses sent back to clients.
The router directs requests to the right controller.
This keeps request handling organized and clear.
Full Transcript
In NestJS, when a client sends an HTTP request, the NestJS router receives it first. The router checks the URL and matches it to a controller based on the route. Once matched, the controller method runs to process the request. The controller returns data, which NestJS sends back as the response. This flow ensures that each request is handled by the correct part of the application, keeping things organized and easy to manage.

Practice

(1/5)
1. In NestJS, why do controllers handle incoming requests?
easy
A. Because they manage server hardware resources
B. Because they store data and manage databases
C. Because they handle user interface rendering
D. Because they organize routes and connect requests to the right code

Solution

  1. Step 1: Understand the role of controllers in NestJS

    Controllers are designed to listen for incoming HTTP requests and decide which code should handle them.
  2. Step 2: Differentiate responsibilities

    Controllers focus on routing and connecting requests to services, not on data storage or UI rendering.
  3. Final Answer:

    Because they organize routes and connect requests to the right code -> Option D
  4. Quick Check:

    Controllers handle routing = A [OK]
Hint: Controllers route requests to code, not store data [OK]
Common Mistakes:
  • Thinking controllers manage data storage
  • Confusing controllers with UI components
  • Assuming controllers handle hardware
2. Which of the following is the correct way to define a controller method to handle GET requests in NestJS?
easy
A. @Controller() get() { return 'Hello'; }
B. function get() { return 'Hello'; }
C. @Get() async handleRequest() { return 'Hello'; }
D. router.get('/hello', () => 'Hello');

Solution

  1. Step 1: Recognize NestJS controller method syntax

    In NestJS, @Get() decorator marks a method to handle GET requests inside a controller class.
  2. Step 2: Compare options

    @Get() async handleRequest() { return 'Hello'; } uses @Get() decorator correctly; others use incorrect syntax or patterns from other frameworks.
  3. Final Answer:

    @Get() async handleRequest() { return 'Hello'; } -> Option C
  4. Quick Check:

    @Get() decorator = C [OK]
Hint: Use @Get() decorator for GET routes in controllers [OK]
Common Mistakes:
  • Using plain functions outside controller classes
  • Confusing @Controller with method decorators
  • Using Express router syntax inside NestJS controllers
3. Given this NestJS controller code, what will be the output when a GET request is made to '/greet'?
@Controller('greet')
export class GreetController {
  @Get()
  sayHello() {
    return 'Hello, NestJS!';
  }
}
medium
A. 404 Not Found error
B. 'Hello, NestJS!'
C. An empty response
D. Server crash due to syntax error

Solution

  1. Step 1: Analyze the route path

    The controller is set to 'greet' and the method handles GET requests at the root of this path, so the full route is '/greet'.
  2. Step 2: Check the method return value

    The sayHello() method returns the string 'Hello, NestJS!'. This string will be sent as the response body.
  3. Final Answer:

    'Hello, NestJS!' -> Option B
  4. Quick Check:

    GET /greet returns method string = A [OK]
Hint: Controller path + method path = full route [OK]
Common Mistakes:
  • Expecting 404 due to missing route
  • Thinking method returns nothing
  • Assuming syntax errors without checking code
4. Identify the error in this NestJS controller code snippet:
@Controller('users')
export class UserController {
  @Post('/create')
  createUser() {
    // missing request body parameter
    return 'User created';
  }
}
medium
A. The method lacks a parameter to receive the request body
B. The @Post decorator is used incorrectly
C. The controller path should not be 'users'
D. The method should return a Promise, not a string

Solution

  1. Step 1: Review method parameters for POST requests

    POST requests usually send data in the request body, which the method should accept as a parameter decorated with @Body().
  2. Step 2: Check the method signature

    The createUser() method has no parameters, so it cannot access the incoming data, which is a common mistake.
  3. Final Answer:

    The method lacks a parameter to receive the request body -> Option A
  4. Quick Check:

    POST methods need @Body() parameter = B [OK]
Hint: POST handlers need @Body() to get data [OK]
Common Mistakes:
  • Ignoring request body in POST methods
  • Misusing decorators on methods
  • Thinking controller path causes error
5. You want to keep your NestJS controller focused only on routing and delegate business logic to a service. Which approach best follows this principle?
hard
A. Inject a service into the controller and call its methods inside controller handlers
B. Handle HTTP requests and business logic in the same controller method
C. Use controllers to directly access the database
D. Write all data processing inside the controller methods

Solution

  1. Step 1: Understand separation of concerns in NestJS

    Controllers should only handle routing and delegate business logic to services to keep code clean and maintainable.
  2. Step 2: Identify the correct pattern

    Injecting a service into the controller and calling its methods inside controller handlers follows this best practice.
  3. Final Answer:

    Inject a service into the controller and call its methods inside controller handlers -> Option A
  4. Quick Check:

    Controllers route, services handle logic = D [OK]
Hint: Use services for logic, controllers for routing [OK]
Common Mistakes:
  • Putting business logic inside controllers
  • Accessing database directly in controllers
  • Mixing routing and logic in one place
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