Beginner LevelExpress JS
How does express.Router() work for building modular route controllers?
❓ Interview Prompt: Explain how to organize large Express applications into modular, maintainable routing files using express.Router().
As an application grows, defining every route on the root 'app' object in a single file becomes unmaintainable. 'express.Router()' creates modular, mountable mini-applications.
How It Works:
1
An 'express.Router()' instance acts as a complete routing and middleware system.
2
You create separate router files for different business domains (e.g. 'userRoutes.js', 'productRoutes.js').
3
In your main application file, you mount these routers onto specific URL prefixes using 'app.use("/prefix", router)'.
4
Any middleware attached to a router ('router.use()') only runs for endpoints mounted under that specific router prefix!
Code Implementation Example
javascript
// routes/userRoutes.js — Modular Router
import express from 'express';
const router = express.Router();
router.use((req, res, next) => {
console.log('User API accessed');
next();
});
// Maps to GET /api/v1/users/
router.get('/', (req, res) => res.json([{ id: 1, name: 'Alice' }]));
// Maps to GET /api/v1/users/:id
router.get('/:id', (req, res) => res.json({ id: req.params.id, name: 'Alice' }));
export default router;
// server.js — Mounting the Router
import express from 'express';
import userRoutes from './routes/userRoutes.js';
const app = express();
app.use('/api/v1/users', userRoutes);
app.listen(3000);💡Structuring Express applications using modular express.Router() files.
🎯 Interview Key Takeaway
Use express.Router() to organize routes into domain-specific modules and mount them onto URL prefixes in your main server file.
#express.Router#Modular Architecture#Routing#Beginner
Back to all Express JS Questions→