This Express app uses conditional middleware to log only requests to paths starting with '/api'. Other requests skip the log.
Express
import express from'express';
const app = express();
// Middleware that logs only API requests
app.use((req, res, next) => {
if (req.path.startsWith('/api')) {
console.log(`API request to ${req.path}`);
}
next();
});
// Simple route
app.get('/api/data', (req, res) => {
res.send('Here is your API data');
});
app.get('/', (req, res) => {
res.send('Welcome to the homepage');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes
Always call next() to avoid hanging requests.
Conditions can check path, method, headers, or any request property.
Use this pattern to keep middleware efficient and avoid unnecessary work.
Summary
Conditional middleware runs only when you want it to.
Use if checks inside middleware to decide execution.
Always call next() to continue request handling.
Practice
(1/5)
1. What is the main purpose of conditional middleware in Express?
easy
A. To run middleware only when certain conditions are met
B. To run all middleware for every request without exception
C. To replace route handlers completely
D. To stop the server from accepting requests
Solution
Step 1: Understand middleware role
Middleware functions process requests and can modify them or respond.
Step 2: Identify conditional middleware purpose
Conditional middleware runs only when a specific condition is true, saving resources and controlling flow.
Final Answer:
To run middleware only when certain conditions are met -> Option A
Quick Check:
Conditional middleware = run only if condition true [OK]
Hint: Think: middleware runs only if condition matches [OK]
Common Mistakes:
Assuming middleware always runs for every request
Confusing middleware with route handlers
Thinking middleware stops server requests
2. Which of the following is the correct way to conditionally execute middleware based on the request path?
easy
A. app.use((req, res, next) => { if (req.path === '/admin') res.send('OK'); });
B. app.use((req, res, next) => { if (req.method === 'POST') res.send('Allowed'); else next(); });
C. app.use((req, res, next) => { if (req.path = '/admin') next(); else next(); });
D. app.use((req, res, next) => { if (req.path === '/admin') next(); else res.send('No access'); });
Solution
Step 1: Check condition syntax
app.use((req, res, next) => { if (req.path === '/admin') next(); else res.send('No access'); }); correctly uses '===' to compare req.path to '/admin'.
Step 2: Verify middleware flow
app.use((req, res, next) => { if (req.path === '/admin') next(); else res.send('No access'); }); calls next() only if path matches; otherwise, it sends a response, stopping further middleware.
Final Answer:
app.use((req, res, next) => { if (req.path === '/admin') next(); else res.send('No access'); }); -> Option D
Quick Check:
Correct condition and flow = app.use((req, res, next) => { if (req.path === '/admin') next(); else res.send('No access'); }); [OK]
Hint: Use '===' for comparison and call next() properly [OK]
Common Mistakes:
Using single '=' instead of '===' for comparison
Not calling next() to continue middleware chain
Sending response without ending middleware properly
If header exists, next() is called but code continues to send 403 response anyway.
Step 2: Identify missing else
Without else, response is sent after next(), causing errors or double responses.
Final Answer:
Missing else block causes response sent twice -> Option C
Quick Check:
Always use else or return after next() [OK]
Hint: Use else or return after next() to avoid double response [OK]
Common Mistakes:
Not using else or return after next()
Assuming next() stops code execution
Ignoring middleware flow after next()
5. You want to create middleware that only runs for POST requests to '/submit' and logs 'Processing submission'. Which code correctly implements this conditional middleware?
hard
A. app.use((req, res, next) => { if (req.path === '/submit' && req.method === 'POST') { console.log('Processing submission'); } next(); });
B. app.use('/submit', (req, res, next) => { if (req.method === 'POST') { console.log('Processing submission'); } next(); });