Discover how middleware turns messy request handling into a smooth, step-by-step process!
Why Middleware execution flow (req, res, next) in Express? - Purpose & Use Cases
Imagine building a web server where you have to manually check every request, handle authentication, log details, and then send a response for each route.
You write the same code again and again inside every route handler.
This manual approach is tiring and error-prone.
If you forget to add a check or log in one route, bugs appear.
It's hard to keep track of what runs first and what happens next.
Middleware functions in Express let you organize code that runs step-by-step for every request.
Each middleware gets the request and response objects, and a next function to pass control forward.
This creates a clear, reusable flow that is easy to manage and debug.
app.get('/data', (req, res) => { if (!req.user) return res.status(401).send('No access'); console.log('Request received'); res.send('Here is your data'); });
app.use(authMiddleware); app.use(loggingMiddleware); app.get('/data', (req, res) => { res.send('Here is your data'); });
It enables building clean, modular servers where each step in request handling is separate and easy to maintain.
Think of a security checkpoint at an airport where each officer checks something different: ID, luggage, boarding pass.
Middleware works like these officers, each doing their job in order before you board the plane.
Manual request handling repeats code and causes bugs.
Middleware runs functions in order, passing control with next().
This creates clear, reusable, and maintainable request flows.
Practice
next() function do in Express middleware?Solution
Step 1: Understand middleware flow
Middleware functions receivereq,res, andnext. Callingnext()tells Express to continue to the next middleware or route.Step 2: Identify the role of
Callingnext()next()does not send a response or stop the chain; it moves control forward.Final Answer:
It passes control to the next middleware or route handler. -> Option AQuick Check:
next() = pass control [OK]
- Thinking next() sends a response
- Assuming next() stops middleware chain
- Confusing next() with modifying req or res
Solution
Step 1: Check middleware function signature
Express middleware must have three parameters:req,res, andnext.Step 2: Verify correct usage of next()
Callingnext()as a function is required to pass control. app.use((req, res, next) => { next(); }); correctly usesnext()with all parameters.Final Answer:
app.use((req, res, next) => { next(); }); -> Option AQuick Check:
Middleware signature + next() call = app.use((req, res, next) => { next(); }); [OK]
- Omitting the next parameter
- Calling next without parentheses
- Using res.next() which does not exist
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?
Solution
Step 1: Trace middleware execution order
The first middleware logs 'A' and calls next(), so control moves to the second middleware.Step 2: Continue to second middleware
The second middleware logs 'B' and calls next(), moving to the third middleware which sends the response.Final Answer:
A B -> Option BQuick Check:
Middleware logs in order = A B [OK]
- Assuming logs appear after response
- Thinking next() skips middleware
- Confusing order of middleware calls
app.use((req, res, next) => {
console.log('Start');
// missing next() call
});
app.use((req, res) => {
res.send('Hello');
});Solution
Step 1: Check middleware flow control
The first middleware logs 'Start' but does not callnext()or send a response, so Express waits indefinitely.Step 2: Understand consequence of missing next()
Without callingnext(), the second middleware never runs, and the client gets no response.Final Answer:
The first middleware never calls next(), so request hangs. -> Option DQuick Check:
Missing next() causes hang [OK]
- Ignoring missing next() causes no response
- Thinking console.log() breaks middleware
- Assuming res.send() is invalid in middleware
Solution
Step 1: Log method and URL
The middleware logsreq.methodandreq.urlcorrectly in all options.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'); }); callsnext()only if method is GET, else sends 405 status. This matches the requirement.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.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 CQuick 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]
- Calling next() then sending response
- Swapping condition logic
- Missing next parameter in middleware
Ready to prove it?
Pass the test and this pattern moves unknown
