Discover how a few lines of middleware can save you hours of repetitive coding!
Why Application-level middleware in Express? - Purpose & Use Cases
Imagine building a web server where you have to check user login, log requests, and handle errors manually inside every route handler.
Manually repeating the same checks and code in every route is tiring, easy to forget, and makes your code messy and hard to fix.
Application-level middleware lets you write these common tasks once and have them run automatically for all routes, keeping your code clean and consistent.
app.get('/data', (req, res) => { if (!req.user) return res.status(401).send('Login required'); console.log('Request to /data'); // handle data });
app.use((req, res, next) => {
if (!req.user) return res.status(401).send('Login required');
next();
});
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});You can add, change, or remove common processing steps easily for all routes without touching each one.
In a shopping website, middleware can check if a user is logged in before letting them add items to the cart, no matter which page they are on.
Manual repetition of checks in every route is slow and error-prone.
Application-level middleware runs shared code automatically for all routes.
This keeps your server code clean, organized, and easier to maintain.
Practice
Solution
Step 1: Understand middleware role
Application-level middleware runs before route handlers to process requests.Step 2: Identify middleware usage
It can modify requests, responses, or decide to stop the request cycle early.Final Answer:
To run code for every request or specific routes before the final handler -> Option AQuick Check:
Middleware runs before handlers [OK]
- Confusing middleware with route handlers
- Thinking middleware creates servers
- Assuming middleware connects databases directly
Solution
Step 1: Recall Express middleware syntax
Express usesapp.use()to add middleware functions.Step 2: Check function parameters
Middleware functions receivereq, res, nextand must callnext()to continue.Final Answer:
app.use((req, res, next) => { console.log('Middleware'); next(); }); -> Option CQuick Check:
app.use with (req, res, next) and next() [OK]
- Using non-existent methods like app.middleware
- Omitting the next parameter or call
- Confusing middleware with route handlers
app.use((req, res, next) => { console.log('First'); next(); });
app.use((req, res, next) => { console.log('Second'); next(); });
app.get('/', (req, res) => { res.send('Hello'); });What will be printed in the console when a GET request is made to '/'?
Solution
Step 1: Understand middleware execution order
Middleware runs in the order they are added withapp.use().Step 2: Trace console logs
First middleware logs 'First' then calls next(), second logs 'Second' then calls next(), then route sends response.Final Answer:
First\nSecond -> Option BQuick Check:
Middleware executes in order added [OK]
- Assuming route handler logs to console
- Thinking middleware runs after route
- Mixing order of middleware execution
app.use((req, res, next) => { console.log('Middleware running'); });
app.get('/', (req, res) => { res.send('Done'); });Solution
Step 1: Check middleware function
The middleware logs a message but does not callnext().Step 2: Understand effect of missing next()
Without callingnext(), the request does not proceed to the route handler, causing the request to hang.Final Answer:
Missing call to next(), request will hang -> Option DQuick Check:
Middleware must call next() to continue [OK]
- Forgetting to call next() in middleware
- Thinking middleware runs after routes
- Assuming middleware syntax is wrong without checking next()
Solution
Step 1: Understand path filtering in middleware
Express allows specifying a path prefix inapp.use(path, middleware)to run middleware only on matching routes.Step 2: Evaluate options
app.use('/admin', (req, res, next) => { console.log('Admin middleware'); next(); }); correctly usesapp.use('/admin', ...)for prefix matching. app.use((req, res, next) => { if(req.url.startsWith('admin')) { console.log('Admin middleware'); } next(); }); has incorrect condition (startsWith('admin')misses leading/, never matches). app.get('/admin', (req, res, next) => { console.log('Admin middleware'); next(); }); is a route handler, not middleware. app.use('*admin', (req, res, next) => { console.log('Admin middleware'); next(); });*adminmatches paths containingadminat the end, not starting with/admin.Final Answer:
app.use('/admin', (req, res, next) => { console.log('Admin middleware'); next(); }); -> Option AQuick Check:
Use app.use with path prefix for selective middleware [OK]
- Using route handlers instead of middleware
- Incorrect conditional checks in global middleware
- Wrong path patterns like wildcards in wrong position
Ready to prove it?
Pass the test and this pattern moves unknown
