Bird
Raised Fist0
Expressframework~10 mins

next() function and flow control in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - next() function and flow control
Request received
↓
Middleware 1
↓
Calls next()?
↓
Middleware 2
↓
Calls next()?
↓
Middleware 3
↓
Final handler or error handler
The request passes through middleware functions one by one. Each middleware calls next() to pass control to the next middleware. If next() is not called, the flow stops and response is sent.
Execution Sample
Express
app.use((req, res, next) => {
  console.log('First middleware');
  next();
});
app.use((req, res) => {
  res.send('Done');
});
This code logs a message in the first middleware, then calls next() to continue to the next middleware which sends the response.
Execution Table
StepMiddlewareActionnext() Called?Next StepOutput
1Middleware 1Logs 'First middleware'YesMiddleware 2No output yet
2Middleware 2Sends response 'Done'NoResponse sentResponse sent: 'Done'
3EndNo more middleware--Request complete
💡 Middleware 2 does not call next(), so response is sent and flow stops.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
reqIncoming request objectPassed to Middleware 1Passed to Middleware 2Handled
resResponse objectPassed to Middleware 1Response sent with 'Done'Closed
nextFunction to call next middlewareCalled at Step 1Not called at Step 2Not called
Key Moments - 2 Insights
Why does the response get sent only after Middleware 2 and not Middleware 1?
Because Middleware 1 calls next(), it passes control to Middleware 2. Middleware 2 sends the response and does not call next(), so the flow stops there (see execution_table Step 2).
What happens if a middleware does not call next() and does not send a response?
The request will hang because the flow stops without sending a response or moving forward. This is why calling next() or sending a response is essential in each middleware.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output after Step 1?
ANo output yet
B'Done' response sent
CError message
DRequest ended
💡 Hint
Check the 'Output' column for Step 1 in the execution_table.
At which step does the response get sent?
AStep 3
BStep 1
CStep 2
DNo response sent
💡 Hint
Look at the 'Action' and 'Output' columns in execution_table rows.
If Middleware 1 did not call next(), what would happen?
AMiddleware 2 would still run
BRequest would hang without response
CResponse would be sent immediately
DAn error would be thrown
💡 Hint
Refer to key_moments about what happens if next() is not called and no response is sent.
Concept Snapshot
Express middleware functions run in order.
Each middleware receives (req, res, next).
Calling next() passes control to next middleware.
If next() is not called and no response sent, request hangs.
Sending response ends the flow.
Use next() to chain middleware or handle errors.
Full Transcript
In Express, when a request comes in, it passes through middleware functions one by one. Each middleware can do something with the request or response. To move to the next middleware, it must call the next() function. If next() is not called, the flow stops. Usually, the last middleware sends a response to the client. If a middleware neither calls next() nor sends a response, the request will hang and never finish. This flow control is important to understand to build Express apps that work correctly.

Practice

(1/5)
1. What does the next() function do in Express middleware?
easy
A. It logs the request details to the console.
B. It passes control to the next middleware or route handler.
C. It restarts the current middleware from the beginning.
D. It ends the request and sends a response to the client.

Solution

  1. Step 1: Understand middleware flow

    Express middleware functions run in sequence. Calling next() moves control to the next middleware or route.
  2. Step 2: Identify next() role

    Calling next() does not send a response but passes control forward, allowing the app to continue processing.
  3. Final Answer:

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

    next() moves control forward [OK]
Hint: Remember: next() moves to next step, doesn't send response [OK]
Common Mistakes:
  • Thinking next() sends a response
  • Confusing next() with ending the request
  • Assuming next() restarts middleware
2. Which of the following is the correct syntax to use next() in an Express middleware function?
easy
A. function(req, res, next) { res.next(); }
B. function(req, res) { next(); }
C. function(req, res, next) { next(); }
D. function(req, res, next) { next; }

Solution

  1. Step 1: Check middleware parameters

    Express middleware must have three parameters: req, res, and next to use next().
  2. Step 2: Verify calling next()

    The correct way to call next() is as a function with parentheses: next();
  3. Final Answer:

    function(req, res, next) { next(); } -> Option C
  4. Quick Check:

    Correct syntax includes next as parameter and calls next() [OK]
Hint: next() must be called as a function with parentheses [OK]
Common Mistakes:
  • Omitting next parameter
  • Calling next without parentheses
  • Using res.next() instead of next()
3. Consider this Express middleware chain:
app.use((req, res, next) => { console.log('First'); next(); });
app.use((req, res, next) => { console.log('Second'); res.send('Done'); });
app.use((req, res, next) => { console.log('Third'); next(); });

What will be printed in the console when a request is made?
medium
A. First\nSecond
B. First\nSecond\nThird
C. Second\nThird
D. First

Solution

  1. Step 1: Trace middleware execution order

    The first middleware logs 'First' and calls next(), so the second middleware runs next.
  2. Step 2: Check response and flow stop

    The second middleware logs 'Second' and sends a response with res.send('Done'). Sending a response ends the request, so the third middleware does not run.
  3. Final Answer:

    First\nSecond -> Option A
  4. Quick Check:

    Response sent stops flow, so third middleware skipped [OK]
Hint: Sending response stops middleware chain immediately [OK]
Common Mistakes:
  • Assuming all middleware run even after response
  • Thinking next() runs after res.send()
  • Ignoring that res.send ends request
4. What is wrong with this Express middleware?
app.use((req, res, next) => {
  console.log('Logging request');
  // forgot to call next or send response
});
medium
A. It will cause the request to hang and never finish.
B. It will automatically call next() after logging.
C. It will send an empty response to the client.
D. It will throw a syntax error.

Solution

  1. Step 1: Identify missing flow control

    The middleware logs a message but neither calls next() nor sends a response.
  2. Step 2: Understand Express behavior

    Without calling next() or sending a response, Express waits indefinitely, causing the request to hang.
  3. Final Answer:

    It will cause the request to hang and never finish. -> Option A
  4. Quick Check:

    Missing next() or response causes hanging [OK]
Hint: Always call next() or send response to finish middleware [OK]
Common Mistakes:
  • Assuming Express auto-calls next()
  • Thinking console.log ends request
  • Expecting default response without sending
5. You want to create middleware that checks if a user is logged in. If not logged in, it should send a 401 response. If logged in, it should continue to the next middleware. Which code correctly uses next() to achieve this?
hard
A. app.use((req, res, next) => { if (!req.user) { next(); } else { res.status(401).send('Unauthorized'); } });
B. app.use((req, res, next) => { next(); if (!req.user) { res.status(401).send('Unauthorized'); } });
C. app.use((req, res, next) => { if (req.user) { res.status(401).send('Unauthorized'); } else { next(); } });
D. app.use((req, res, next) => { if (!req.user) { res.status(401).send('Unauthorized'); } else { next(); } });

Solution

  1. Step 1: Check user login condition

    If req.user is missing, the middleware should send a 401 Unauthorized response immediately.
  2. Step 2: Use next() correctly

    If the user is logged in, call next() to pass control to the next middleware or route handler.
  3. Final Answer:

    Middleware sends 401 if no user, else calls next() -> Option D
  4. Quick Check:

    Send response before next(), or call next() to continue [OK]
Hint: Send response first if unauthorized; call next() only if authorized [OK]
Common Mistakes:
  • Calling next() before sending response
  • Swapping conditions for sending response
  • Calling next() after sending response
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