0
0
NestJSframework~10 mins

Why middleware processes requests before handlers in NestJS - Visual Breakdown

Choose your learning style9 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.