Bird
Raised Fist0
NestJSframework~10 mins

Why middleware processes requests before handlers in NestJS - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why middleware processes requests before handlers
Incoming HTTP Request
↓
Middleware Processes Request
↓
Pass to Next Middleware or Handler
↓
Route Handler Executes
↓
Response Sent Back
The request first goes through middleware which can modify or check it before passing it to the route handler that sends the response.
Execution Sample
NestJS
app.use((req, res, next) => {
  console.log('Middleware start');
  req.processed = true;
  next();
});
app.get('/', (req, res) => {
  res.sent = true;
  res.send('Hello');
});
Middleware logs a message before the route handler sends 'Hello' as response.
Execution Table
StepActionMiddleware LogHandler CalledResponse Sent
1Request receivedNoNo
2Middleware runsMiddleware startNoNo
3Middleware calls next()Middleware startYesNo
4Handler runsMiddleware startYesNo
5Handler sends responseMiddleware startYesHello
💡 Response sent by handler, request processing ends
Variable Tracker
VariableStartAfter MiddlewareAfter HandlerFinal
req.processedundefinedtrue (middleware sets flag)truetrue
res.sentundefinedundefinedtrue (handler sends)true
Key Moments - 2 Insights
Why does middleware run before the handler?
Middleware runs first to allow pre-processing like logging or authentication before the handler runs, as shown in execution_table step 2 and 3.
What happens if middleware does not call next()?
If middleware does not call next(), the handler never runs and response is not sent, stopping the flow early (not shown in table but implied).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step does the handler start running?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Check the 'Handler Called' column in execution_table rows
According to variable_tracker, when does res.sent become true?
AAfter Middleware
BAfter Handler
CAt Start
DNever
💡 Hint
Look at the 'res.sent' row in variable_tracker
If middleware skipped calling next(), what would happen to the handler?
AHandler runs anyway
BHandler runs twice
CHandler never runs
DMiddleware runs again
💡 Hint
Recall key_moments explanation about next() importance
Concept Snapshot
Middleware runs before route handlers to process requests early.
It can modify requests or block them.
Middleware must call next() to continue flow.
Handlers run after middleware to send responses.
This order ensures control and flexibility.
Full Transcript
In NestJS, when a request comes in, it first passes through middleware. Middleware can do things like logging or checking if the user is allowed. It must call next() to let the request continue. After middleware, the route handler runs and sends the response. If middleware does not call next(), the handler never runs and the request stops there. This order helps keep control over requests and responses.

Practice

(1/5)
1. Why does middleware in NestJS process requests before the route handlers?
easy
A. To delay the request processing intentionally
B. To send the response after the handler finishes
C. To replace the route handler completely
D. To prepare or check the request before the handler uses it

Solution

  1. Step 1: Understand middleware role

    Middleware runs before handlers to prepare or validate requests, like checking authentication or adding data.
  2. Step 2: Compare with other options

    Middleware does not send responses after handlers or replace handlers; it only processes requests early.
  3. Final Answer:

    To prepare or check the request before the handler uses it -> Option D
  4. Quick Check:

    Middleware prepares requests = D [OK]
Hint: Middleware runs first to prep requests before handlers [OK]
Common Mistakes:
  • Thinking middleware runs after handlers
  • Believing middleware replaces handlers
  • Assuming middleware delays requests
2. Which of the following is the correct way to continue request processing inside a NestJS middleware?
easy
A. Return the response directly
B. Call next() function
C. Throw an error to stop processing
D. Call the route handler manually

Solution

  1. Step 1: Identify middleware flow control

    In NestJS, calling next() passes control to the next middleware or handler.
  2. Step 2: Eliminate incorrect options

    Returning response or throwing error stops flow; calling handler manually is not standard.
  3. Final Answer:

    Call next() function -> Option B
  4. Quick Check:

    Use next() to continue middleware chain [OK]
Hint: Always call next() to move forward in middleware [OK]
Common Mistakes:
  • Forgetting to call next(), causing request hang
  • Trying to call handler directly inside middleware
  • Returning response without next() when not ending request
3. Given this NestJS middleware code snippet, what will be logged first when a request arrives?
export function logger(req, res, next) {
  console.log('Middleware start');
  next();
  console.log('Middleware end');
}
medium
A. "Middleware start" then "Middleware end"
B. "Middleware end" then "Middleware start"
C. Only "Middleware start" is logged
D. No logs appear because next() stops execution

Solution

  1. Step 1: Analyze middleware execution order

    Console logs before and after next() run synchronously; first logs "Middleware start".
  2. Step 2: Understand next() behavior

    Calling next() passes control but does not pause middleware; "Middleware end" logs after next() call.
  3. Final Answer:

    "Middleware start" then "Middleware end" -> Option A
  4. Quick Check:

    Logs before and after next() run in order [OK]
Hint: Logs before and after next() run in sequence [OK]
Common Mistakes:
  • Thinking next() pauses middleware execution
  • Assuming logs after next() run later
  • Believing next() stops middleware code
4. You wrote this NestJS middleware but requests never reach the handler. What is the problem?
export function authMiddleware(req, res, next) {
  if (!req.headers.authorization) {
    res.status(401).send('Unauthorized');
    return;
  }
  next();
}
medium
A. Middleware must not send responses directly
B. Authorization header check is incorrect syntax
C. next() is called even after sending response, causing errors
D. next() should be called before checking headers

Solution

  1. Step 1: Review middleware flow control

    If authorization header is missing, response is sent but next() is still called, causing request to continue incorrectly.
  2. Step 2: Fix flow by returning early

    To stop processing after sending response, return immediately without calling next().
  3. Final Answer:

    next() is called even after sending response, causing errors -> Option C
  4. Quick Check:

    Don't call next() after sending response [OK]
Hint: Return after sending response to avoid calling next() [OK]
Common Mistakes:
  • Calling next() after response ends
  • Not returning early to stop middleware
  • Misunderstanding middleware flow control
5. You want to add a middleware that adds a timestamp to every request before handlers run. Which approach correctly ensures the timestamp is available in the handler?
hard
A. Add req.timestamp = Date.now() in middleware, then call next()
B. Call next() first, then add req.timestamp after
C. Add timestamp in the handler, not middleware
D. Send timestamp in response headers from middleware

Solution

  1. Step 1: Understand middleware purpose

    Middleware runs before handlers, so adding data to req here makes it available later.
  2. Step 2: Correct order of operations

    Assign req.timestamp before calling next() so handlers see the value.
  3. Final Answer:

    Add req.timestamp = Date.now() in middleware, then call next() -> Option A
  4. Quick Check:

    Add data before next() to share with handlers [OK]
Hint: Set request data before next() to share with handlers [OK]
Common Mistakes:
  • Adding data after next(), so handlers miss it
  • Trying to add data in handlers instead of middleware
  • Sending data only in response headers
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