What if you could handle all common tasks for every request with just a few simple functions?
Why Middleware concept and execution flow in Node.js? - Purpose & Use Cases
Imagine building a web server where you have to check user login, log requests, handle errors, and parse data manually for every single route.
Doing all these checks and tasks manually in each route is repetitive, easy to forget, and makes your code messy and hard to maintain.
Middleware lets you write small functions that run in order for every request, handling tasks like logging, authentication, and errors automatically and cleanly.
app.get('/data', (req, res) => { if (!req.user) { res.status(401).send('Login required'); return; } console.log('Request received'); /* handle data */ });
app.use(loggingMiddleware); app.use(authMiddleware); app.get('/data', (req, res) => { /* handle data */ });Middleware enables building clear, reusable, and organized request handling that scales easily as your app grows.
In a shopping website, middleware can check if a user is logged in before allowing checkout, log every purchase request, and catch errors without repeating code in every route.
Manual checks in every route cause repeated and messy code.
Middleware runs functions in order for all requests automatically.
This makes your server code cleaner, reusable, and easier to maintain.
Practice
Solution
Step 1: Understand middleware role and compare options
Middleware functions run before route handlers to process requests. Only To run code on requests before they reach the route handlers describes middleware's role correctly; others describe unrelated tasks.Final Answer:
To run code on requests before they reach the route handlers -> Option DQuick Check:
Middleware = Pre-route code [OK]
- Thinking middleware sends responses directly
- Confusing middleware with database logic
- Assuming middleware styles pages
Solution
Step 1: Recall Express middleware syntax and check options
Middleware uses app.use() with (req, res, next) parameters. Only app.use((req, res, next) => { console.log('Middleware'); next(); }); uses app.use() and calls next(), which is correct middleware syntax.Final Answer:
app.use((req, res, next) => { console.log('Middleware'); next(); }); -> Option BQuick Check:
Middleware = app.use + next() [OK]
- Using app.get instead of app.use for middleware
- Missing next() call inside middleware
- Using non-existent app.middleware method
app.use((req, res, next) => { console.log('First'); next(); });
app.use((req, res, next) => { console.log('Second'); next(); });
app.get('/', (req, res) => { res.send('Done'); });What will be printed in the console when a GET request is made to '/'?
Solution
Step 1: Understand middleware execution order and route handler
Middleware runs in the order added: first prints 'First', then calls next(), second prints 'Second'. After middleware, route handler sends response but does not print to console.Final Answer:
First\nSecond -> Option AQuick Check:
Middleware order = console logs order [OK]
- Assuming route handler logs to console
- Thinking middleware runs in reverse order
- Missing next() causes no further logs
app.use((req, res, next) => { console.log('Start'); });
app.get('/', (req, res) => { res.send('Hello'); });Solution
Step 1: Check middleware function and request flow effect
The middleware logs 'Start' but does not call next(), so it blocks further processing. Without next(), the route handler never runs, so the request hangs.Final Answer:
It never calls next(), so the request hangs -> Option CQuick Check:
Missing next() blocks request [OK]
- Forgetting to call next() in middleware
- Calling next() multiple times
- Confusing middleware parameters
Solution
Step 1: Check middleware order, next() calls, and route handler execution
app.use((req, res, next) => { console.log('Time:', Date.now()); next(); });\napp.use((req, res, next) => { if(req.user) next(); else res.status(401).send('Unauthorized'); });\napp.get('/', (req, res) => { res.send('Welcome'); }); runs time logger first, calls next(), then auth check middleware, which calls next() or sends response. Only if both middleware call next(), the route handler runs and sends 'Welcome'.Final Answer:
app.use((req, res, next) => { console.log('Time:', Date.now()); next(); });\napp.use((req, res, next) => { if(req.user) next(); else res.status(401).send('Unauthorized'); });\napp.get('/', (req, res) => { res.send('Welcome'); }); -> Option AQuick Check:
Middleware order + next() = correct flow [OK]
- Missing next() in first middleware
- Reversing middleware order
- Using app.get instead of app.use for middleware
Ready to prove it?
Pass the test and this pattern moves unknown
