Bird
Raised Fist0
Expressframework~10 mins

Middleware execution flow (req, res, next) in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Middleware execution flow (req, res, next)
Request Received
↓
Middleware 1
↓
Calls next()
→Middleware 2
↓
Calls next()
→Middleware 3
↓
Sends Response
↓
Response Sent
The request passes through each middleware in order. Each middleware can call next() to pass control to the next one or send a response to end the chain.
Execution Sample
Express
app.use((req, res, next) => {
  console.log('First middleware');
  next();
});
app.use((req, res, next) => {
  console.log('Second middleware');
  res.send('Done');
});
Two middlewares run in order; the first logs and calls next(), the second logs and sends a response.
Execution Table
StepMiddlewareActionnext() Called?Response Sent?Console Output
1Middleware 1Logs 'First middleware'YesNoFirst middleware
2Middleware 2Logs 'Second middleware' and sends responseNoYesSecond middleware
3EndResponse sent, no further middlewareN/AYesN/A
💡 Response sent in Middleware 2, so middleware chain stops.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
reqIncoming request objectPassed to Middleware 2Passed to Middleware 2Used to send response
resResponse objectNot sentResponse sentResponse sent
nextFunction to call next middlewareCalledNot calledN/A
Key Moments - 3 Insights
Why does the second middleware run after the first?
Because the first middleware calls next(), which passes control to the next middleware as shown in execution_table step 1.
What happens if a middleware sends a response without calling next()?
The middleware chain stops immediately, no further middleware runs, as seen in execution_table step 2 and exit_note.
Can next() be called multiple times in one middleware?
No, calling next() more than once can cause errors or unexpected behavior. Each middleware should call next() once or send a response.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the console output after step 1?
A'First middleware'
B'Second middleware'
C'Done'
DNo output yet
💡 Hint
Check the 'Console Output' column for step 1 in execution_table.
At which step does the response get sent?
AStep 1
BStep 3
CStep 2
DNo response sent
💡 Hint
Look at the 'Response Sent?' column in execution_table.
If Middleware 1 did not call next(), what would happen?
AResponse would be sent immediately
BMiddleware chain would stop after Middleware 1
CMiddleware 2 would still run
DAn error would occur
💡 Hint
Refer to the concept_flow and key_moments about next() usage.
Concept Snapshot
Middleware in Express runs in order.
Each middleware gets req, res, next.
Call next() to pass control to next middleware.
Send response to end chain.
If next() not called and no response sent, request hangs.
Full Transcript
In Express, middleware functions run one after another when a request comes in. Each middleware receives three things: the request object, the response object, and a next function. When a middleware finishes its job, it can call next() to let the next middleware run. If it sends a response instead, the chain stops there. This flow ensures that requests are handled step-by-step, and responses are sent only once. The execution table shows how the first middleware logs a message and calls next(), then the second middleware logs another message and sends the response, stopping the chain.

Practice

(1/5)
1. What does the next() function do in Express middleware?
easy
A. It passes control to the next middleware or route handler.
B. It sends the response back to the client immediately.
C. It stops the middleware chain and ends the request.
D. It modifies the request object permanently.

Solution

  1. Step 1: Understand middleware flow

    Middleware functions receive req, res, and next. Calling next() tells Express to continue to the next middleware or route.
  2. Step 2: Identify the role of next()

    Calling next() does not send a response or stop the chain; it moves control forward.
  3. Final Answer:

    It passes control to the next middleware or route handler. -> Option A
  4. Quick Check:

    next() = pass control [OK]
Hint: Remember: next() moves to the next step in middleware [OK]
Common Mistakes:
  • Thinking next() sends a response
  • Assuming next() stops middleware chain
  • Confusing next() with modifying req or res
2. Which of the following is the correct way to define middleware in Express?
easy
A. app.use((req, res, next) => { next(); });
B. app.use((req, res) => { next(); });
C. app.use((req, res, next) => { res.next(); });
D. app.use((req, res, next) => { next; });

Solution

  1. Step 1: Check middleware function signature

    Express middleware must have three parameters: req, res, and next.
  2. Step 2: Verify correct usage of next()

    Calling next() as a function is required to pass control. app.use((req, res, next) => { next(); }); correctly uses next() with all parameters.
  3. Final Answer:

    app.use((req, res, next) => { next(); }); -> Option A
  4. Quick Check:

    Middleware signature + next() call = app.use((req, res, next) => { next(); }); [OK]
Hint: Middleware needs (req, res, next) and call next() as a function [OK]
Common Mistakes:
  • Omitting the next parameter
  • Calling next without parentheses
  • Using res.next() which does not exist
3. Consider this Express middleware chain:
app.use((req, res, next) => { console.log('A'); next(); });
app.use((req, res, next) => { console.log('B'); next(); });
app.use((req, res) => { res.send('Done'); });

What will be printed in the console when a request is made?
medium
A. A
B. A B
C. B A
D. No output

Solution

  1. Step 1: Trace middleware execution order

    The first middleware logs 'A' and calls next(), so control moves to the second middleware.
  2. Step 2: Continue to second middleware

    The second middleware logs 'B' and calls next(), moving to the third middleware which sends the response.
  3. Final Answer:

    A B -> Option B
  4. Quick Check:

    Middleware logs in order = A B [OK]
Hint: Middleware runs in order; next() moves forward [OK]
Common Mistakes:
  • Assuming logs appear after response
  • Thinking next() skips middleware
  • Confusing order of middleware calls
4. What is the problem with this middleware code?
app.use((req, res, next) => {
  console.log('Start');
  // missing next() call
});
app.use((req, res) => {
  res.send('Hello');
});
medium
A. The second middleware is missing next parameter.
B. console.log() causes an error in middleware.
C. res.send() cannot be called in middleware.
D. The first middleware never calls next(), so request hangs.

Solution

  1. Step 1: Check middleware flow control

    The first middleware logs 'Start' but does not call next() or send a response, so Express waits indefinitely.
  2. Step 2: Understand consequence of missing next()

    Without calling next(), the second middleware never runs, and the client gets no response.
  3. Final Answer:

    The first middleware never calls next(), so request hangs. -> Option D
  4. Quick Check:

    Missing next() causes hang [OK]
Hint: Always call next() or send response to avoid hanging [OK]
Common Mistakes:
  • Ignoring missing next() causes no response
  • Thinking console.log() breaks middleware
  • Assuming res.send() is invalid in middleware
5. You want to create middleware that logs request method and URL, then passes control only if the method is GET. Otherwise, it should send a 405 status. Which code correctly implements this?
hard
A. app.use((req, res, next) => { console.log(req.method, req.url); next(); res.status(405).send('Method Not Allowed'); });
B. app.use((req, res, next) => { console.log(req.method, req.url); if (req.method === 'GET') res.send('OK'); else next(); });
C. app.use((req, res, next) => { console.log(req.method, req.url); if (req.method === 'GET') next(); else res.status(405).send('Method Not Allowed'); });
D. app.use((req, res) => { console.log(req.method, req.url); if (req.method !== 'GET') next(); else res.status(405).send('Method Not Allowed'); });

Solution

  1. Step 1: Log method and URL

    The middleware logs req.method and req.url correctly in all options.
  2. Step 2: Control flow based on method

    app.use((req, res, next) => { console.log(req.method, req.url); if (req.method === 'GET') next(); else res.status(405).send('Method Not Allowed'); }); calls next() only if method is GET, else sends 405 status. This matches the requirement.
  3. Step 3: Identify incorrect options

    app.use((req, res, next) => { console.log(req.method, req.url); if (req.method === 'GET') res.send('OK'); else next(); }); sends 'OK' on GET instead of passing control. app.use((req, res, next) => { console.log(req.method, req.url); next(); res.status(405).send('Method Not Allowed'); }); calls next() then tries to send response (invalid). app.use((req, res) => { console.log(req.method, req.url); if (req.method !== 'GET') next(); else res.status(405).send('Method Not Allowed'); }); lacks next parameter and reverses logic.
  4. Final Answer:

    app.use((req, res, next) => { console.log(req.method, req.url); if (req.method === 'GET') next(); else res.status(405).send('Method Not Allowed'); }); -> Option C
  5. Quick Check:

    next() only on GET, else 405 = app.use((req, res, next) => { console.log(req.method, req.url); if (req.method === 'GET') next(); else res.status(405).send('Method Not Allowed'); }); [OK]
Hint: Call next() only for GET; send 405 otherwise [OK]
Common Mistakes:
  • Calling next() then sending response
  • Swapping condition logic
  • Missing next parameter in middleware
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