Application-level middleware helps you run code for every request your app gets. It can change requests, responses, or stop the request if needed.
Application-level middleware in Express
Introduction
Syntax
Express
app.use(function (req, res, next) {
// your code here
next();
});Middleware functions take three arguments:
req, res, and next.Always call
next() to pass control to the next middleware or route.Examples
Express
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});/admin and blocks users who are not admins.Express
app.use('/admin', (req, res, next) => { if (!req.user || !req.user.isAdmin) { return res.status(403).send('Access denied'); } next(); });
Express
app.use(express.json());
Sample Program
This example shows an application-level middleware that logs every request method and URL. Then it responds with a greeting on the home page.
Express
import express from 'express'; const app = express(); // Application-level middleware to log requests app.use((req, res, next) => { console.log(`Received ${req.method} request for ${req.url}`); next(); }); // Simple route app.get('/', (req, res) => { res.send('Hello from Express!'); }); // Start server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Important Notes
Middleware order matters: Express runs them in the order you add them.
If you forget to call next(), the request will hang and never reach routes.
You can add middleware for specific paths by passing the path as the first argument to app.use().
Summary
Application-level middleware runs for every request or for specific paths.
It can modify requests, responses, or stop requests early.
Always call next() to continue the request cycle.
Practice
1. What is the main purpose of application-level middleware in Express?
easy
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]
Hint: Middleware runs before routes to process requests [OK]
Common Mistakes:
- Confusing middleware with route handlers
- Thinking middleware creates servers
- Assuming middleware connects databases directly
2. Which of the following is the correct syntax to add application-level middleware in Express?
easy
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]
Hint: Middleware uses app.use with three parameters and calls next() [OK]
Common Mistakes:
- Using non-existent methods like app.middleware
- Omitting the next parameter or call
- Confusing middleware with route handlers
3. Consider this Express code snippet:
What will be printed in the console when a GET request is made to '/'?
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 '/'?
medium
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]
Hint: Middleware logs appear in order of app.use calls [OK]
Common Mistakes:
- Assuming route handler logs to console
- Thinking middleware runs after route
- Mixing order of middleware execution
4. What is the problem with this middleware code?
app.use((req, res, next) => { console.log('Middleware running'); });
app.get('/', (req, res) => { res.send('Done'); });medium
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]
Hint: Always call next() in middleware to avoid hanging requests [OK]
Common Mistakes:
- Forgetting to call next() in middleware
- Thinking middleware runs after routes
- Assuming middleware syntax is wrong without checking next()
5. You want to create middleware that only runs for routes starting with '/admin'. Which is the correct way to apply this middleware?
hard
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]
Hint: Use app.use('/path', middleware) to target specific routes [OK]
Common Mistakes:
- Using route handlers instead of middleware
- Incorrect conditional checks in global middleware
- Wrong path patterns like wildcards in wrong position
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
