Performance: Router-level middleware
This affects server response time and throughput by controlling how requests are processed and routed.
router.use('/specific-path', (req, res, next) => { /* logic */ next(); });
app.use((req, res, next) => { /* heavy logic */ next(); });| Pattern | CPU Usage | Blocking | Request Latency | Verdict |
|---|---|---|---|---|
| Global middleware on all routes | High | No | Increased | [X] Bad |
| Middleware scoped to specific routes | Low | No | Reduced | [OK] Good |
| Synchronous blocking middleware | High | Yes | Severely Increased | [X] Bad |
| Asynchronous non-blocking middleware | Moderate | No | Optimized | [OK] Good |
router.use().router.middleware, app.useRouter, and router.add are not valid Express methods.const express = require('express');
const router = express.Router();
router.use((req, res, next) => {
console.log('Middleware A');
next();
});
router.get('/test', (req, res) => {
res.send('Hello from test');
});
module.exports = router;/test on this router?const router = require('express').Router();
router.use((req, res, next) => {
console.log('First middleware');
next();
});
router.get('/hello', (req, res) => {
res.send('Hello World');
});
router.use((req, res) => {
});/api in your Express app. You create a router and add middleware like this:const express = require('express');
const app = express();
const apiRouter = express.Router();
apiRouter.use((req, res, next) => {
console.log('API request:', req.method, req.url);
next();
});
apiRouter.get('/users', (req, res) => {
res.send('User list');
});
app.use('/api', apiRouter);
app.get('/', (req, res) => {
res.send('Home');
});/api/users and /?Pass the test and this pattern moves unknown