Using the next() Function for Middleware Flow Control in Express
📖 Scenario: You are building a simple Express server that handles requests with multiple middleware functions. Middleware functions help process requests step-by-step before sending a response.Understanding how to use the next() function is important to control the flow between these middleware functions.
🎯 Goal: Build an Express server with two middleware functions. The first middleware will log a message and then call next() to pass control to the second middleware, which sends a response to the client.
📋 What You'll Learn
Create an Express app instance
Write a middleware function named logger that logs 'Request received' and calls next()
Write a middleware function named responder that sends 'Hello from Express!' as the response
Use app.use() to add both middleware functions in the correct order
💡 Why This Matters
🌍 Real World
Middleware functions are used in real Express apps to handle logging, authentication, data parsing, and more, controlling how requests flow through the server.
💼 Career
Understanding next() and middleware flow is essential for backend developers working with Express to build scalable and maintainable web servers.
Progress0 / 4 steps
1
Set up Express app
Write code to import Express and create an app instance called app.
Express
Hint
Use import express from 'express' and then const app = express() to create the app.
2
Create logger middleware
Create a middleware function named logger that takes req, res, and next as parameters. Inside it, log 'Request received' and then call next().
Express
Hint
Define logger as a function with three parameters and call next() after logging.
3
Create responder middleware
Create a middleware function named responder that takes req and res as parameters and sends the text 'Hello from Express!' as the response.
Express
Hint
Define responder as a function with req and res and use res.send() to send the response.
4
Use middleware in app
Use app.use() to add the logger middleware first, then the responder middleware, so requests flow through both.
Express
Hint
Call app.use() twice, first with logger, then with responder.
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
Step 1: Understand middleware flow
Express middleware functions run in sequence. Calling next() moves control to the next middleware or route.
Step 2: Identify next() role
Calling next() 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 B
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
Step 1: Check middleware parameters
Express middleware must have three parameters: req, res, and next to use next().
Step 2: Verify calling next()
The correct way to call next() is as a function with parentheses: next();
Final Answer:
function(req, res, next) { next(); } -> Option C
Quick Check:
Correct syntax includes next as parameter and calls next() [OK]
Hint: next() must be called as a function with parentheses [OK]
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
Step 1: Trace middleware execution order
The first middleware logs 'First' and calls next(), so the second middleware runs next.
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.
Final Answer:
First\nSecond -> Option A
Quick Check:
Response sent stops flow, so third middleware skipped [OK]
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
Step 1: Identify missing flow control
The middleware logs a message but neither calls next() nor sends a response.
Step 2: Understand Express behavior
Without calling next() 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 A
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
Step 1: Check user login condition
If req.user is missing, the middleware should send a 401 Unauthorized response immediately.
Step 2: Use next() correctly
If the user is logged in, call next() to pass control to the next middleware or route handler.
Final Answer:
Middleware sends 401 if no user, else calls next() -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.