The next() function helps move from one step to the next in Express. It controls how requests flow through different parts of your app.
next() function and flow control in Express
function middleware(req, res, next) {
// your code here
next(); // pass control to next middleware
}The next parameter is a function you call to continue the request flow.
If you don't call next() or send a response, the request will hang.
next() to continue.app.use((req, res, next) => {
console.log('First middleware');
next();
});next().app.use((req, res, next) => {
if (!req.user) {
res.status(401).send('Unauthorized');
} else {
next();
}
});next(err).app.use((err, req, res, next) => {
console.error(err);
res.status(500).send('Server error');
});This app uses two middleware functions before the final route handler. The first logs the request method. The second checks if the query parameter name exists. If missing, it sends an error response. Otherwise, it calls next() to reach the final handler that greets the user.
import express from 'express'; const app = express(); // Middleware 1: Logs request method app.use((req, res, next) => { console.log(`Request method: ${req.method}`); next(); }); // Middleware 2: Checks for a query param 'name' app.use((req, res, next) => { if (!req.query.name) { res.status(400).send('Name query param missing'); } else { next(); } }); // Final handler: Sends greeting app.get('/', (req, res) => { res.send(`Hello, ${req.query.name}!`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always call next() or send a response to avoid hanging requests.
Use next(err) to pass errors to error-handling middleware.
Order of middleware matters; Express runs them in the order you add them.
next() moves control to the next middleware or route.
It helps split your app into small steps that run one after another.
Calling next() or sending a response is required to finish handling a request.
Practice
next() function do in Express middleware?Solution
Step 1: Understand middleware flow
Express middleware functions run in sequence. Callingnext()moves control to the next middleware or route.Step 2: Identify
Callingnext()rolenext()does not send a response but passes control forward, allowing the app to continue processing.Final Answer:
It passes control to the next middleware or route handler. -> Option BQuick Check:
next()moves control forward [OK]
- Thinking next() sends a response
- Confusing next() with ending the request
- Assuming next() restarts middleware
next() in an Express middleware function?Solution
Step 1: Check middleware parameters
Express middleware must have three parameters:req,res, andnextto usenext().Step 2: Verify calling next()
The correct way to callnext()is as a function with parentheses:next();Final Answer:
function(req, res, next) { next(); } -> Option CQuick Check:
Correct syntax includes next as parameter and calls next() [OK]
- Omitting next parameter
- Calling next without parentheses
- Using res.next() instead of next()
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?
Solution
Step 1: Trace middleware execution order
The first middleware logs 'First' and callsnext(), so the second middleware runs next.Step 2: Check response and flow stop
The second middleware logs 'Second' and sends a response withres.send('Done'). Sending a response ends the request, so the third middleware does not run.Final Answer:
First\nSecond -> Option AQuick Check:
Response sent stops flow, so third middleware skipped [OK]
- Assuming all middleware run even after response
- Thinking next() runs after res.send()
- Ignoring that res.send ends request
app.use((req, res, next) => {
console.log('Logging request');
// forgot to call next or send response
});Solution
Step 1: Identify missing flow control
The middleware logs a message but neither callsnext()nor sends a response.Step 2: Understand Express behavior
Without callingnext()or sending a response, Express waits indefinitely, causing the request to hang.Final Answer:
It will cause the request to hang and never finish. -> Option AQuick Check:
Missing next() or response causes hanging [OK]
- Assuming Express auto-calls next()
- Thinking console.log ends request
- Expecting default response without sending
next() to achieve this?Solution
Step 1: Check user login condition
Ifreq.useris missing, the middleware should send a 401 Unauthorized response immediately.Step 2: Use next() correctly
If the user is logged in, callnext()to pass control to the next middleware or route handler.Final Answer:
Middleware sends 401 if no user, else calls next() -> Option DQuick Check:
Send response before next(), or call next() to continue [OK]
- Calling next() before sending response
- Swapping conditions for sending response
- Calling next() after sending response
Ready to prove it?
Pass the test and this pattern moves unknown
