Performance: Mounting routers with app.use
This affects the server response time and middleware execution order, impacting how quickly routes are matched and handled.
const express = require('express'); const app = express(); const usersRouter = express.Router(); const productsRouter = express.Router(); usersRouter.use((req, res, next) => { console.log('Logging users requests'); next(); }); usersRouter.get('/', (req, res) => { res.send('Users list'); }); productsRouter.get('/', (req, res) => { res.send('Products list'); }); app.use('/users', usersRouter); app.use('/products', productsRouter);
const express = require('express'); const app = express(); app.use((req, res, next) => { console.log('Logging every request'); next(); }); app.get('/users', (req, res) => { res.send('Users list'); }); app.get('/products', (req, res) => { res.send('Products list'); });
| Pattern | Middleware Execution | Route Matching | Response Time Impact | Verdict |
|---|---|---|---|---|
| Global middleware on app.use | Runs on every request | Matches all routes | Increases response time due to unnecessary middleware | [X] Bad |
| Scoped routers with app.use('/path') | Runs only on matching routes | Matches specific routes efficiently | Reduces response time by limiting middleware | [OK] Good |
app.use to mount routers in Express?app.use doesapp.use mounts middleware or routers at a specified path, grouping routes.userRouter on the path /users using app.use?app.use syntaxapp.use(path, router) to mount a router at a path.app.use('/users', userRouter); which is correct. Others have wrong order or method.const express = require('express');
const app = express();
const userRouter = express.Router();
userRouter.get('/', (req, res) => res.send('User list'));
app.use('/users', userRouter);
userRouter is mounted at '/users', the full path is '/users/' to reach the route.const express = require('express');
const app = express();
const router = express.Router();
router.get('/info', (req, res) => res.send('Info page'));
app.use(router, '/info');app.use argument orderapp.use(path, router), but here it is reversed.adminRouter and userRouter, so that /admin/dashboard and /users/profile work correctly. Which code correctly mounts both routers?app.use('/admin', adminRouter); and app.use('/users', userRouter);, which is correct. app.use(adminRouter, '/admin');\napp.use(userRouter, '/users'); swaps arguments, C mounts at full paths (not base), D uses app.get which is incorrect for mounting routers.Pass the test and this pattern moves unknown