Performance: Why modular routing matters
Modular routing affects server response time and code maintainability, indirectly impacting how fast the server can handle requests and send responses.
const express = require('express'); const app = express(); const usersRouter = require('./routes/users'); const productsRouter = require('./routes/products'); const ordersRouter = require('./routes/orders'); app.use('/users', usersRouter); app.use('/products', productsRouter); app.use('/orders', ordersRouter); app.listen(3000);
const express = require('express'); const app = express(); app.get('/users', (req, res) => { /* handle users */ }); app.get('/products', (req, res) => { /* handle products */ }); app.get('/orders', (req, res) => { /* handle orders */ }); // Many routes all defined in one file app.listen(3000);
| Pattern | Route Matching Complexity | Code Maintainability | Server Response Time | Verdict |
|---|---|---|---|---|
| Single file with many routes | High (linear with routes count) | Low (hard to maintain) | Slower as routes grow | [X] Bad |
| Modular routing with express.Router() | Lower (grouped by path prefix) | High (easy to maintain) | Faster and scalable | [OK] Good |
express.Router()./users?
const express = require('express');
const app = express();
const userRouter = express.Router();
userRouter.get('/', (req, res) => res.send('User list'));
app.use('/users', userRouter);
app.listen(3000);userRouter handles GET requests at '/' and is mounted at '/users'. So, '/users' triggers the router's '/' route.const express = require('express');
const app = express();
const router = express.Router();
router.get('/items', (req, res) => res.send('Items list'));
app.use(router);
app.listen(3000);app.use(router), so its routes like GET /items are registered directly on the app and reachable at /items.express.Router() as a factory function, not new; router.get is correct for modularity; app.listen can follow route definitions.adminRouter handling / and userRouter handling /. You mount them as:
app.use('/admin', adminRouter);
app.use('/admin', userRouter);
What problem can arise and how to fix it?Pass the test and this pattern moves unknown