Performance: Application-level middleware
This affects server response time and how quickly the server processes requests before sending responses.
app.use(async (req, res, next) => { await someAsyncOperation(); next(); });
app.use((req, res, next) => {
// heavy synchronous processing
for (let i = 0; i < 1e7; i++) {}
next();
});| Pattern | Middleware Calls | Blocking | CPU Usage | Verdict |
|---|---|---|---|---|
| Heavy synchronous middleware on all routes | Many | Yes | High | [X] Bad |
| Asynchronous middleware on specific routes | Few | No | Low | [OK] Good |
app.use() to add middleware functions.req, res, next and must call next() to continue.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'); });app.use().app.use((req, res, next) => { console.log('Middleware running'); });
app.get('/', (req, res) => { res.send('Done'); });next().next(), the request does not proceed to the route handler, causing the request to hang.app.use(path, middleware) to run middleware only on matching routes.app.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(); }); *admin matches paths containing admin at the end, not starting with /admin.Pass the test and this pattern moves unknown