What is express.Router and why use it?
express.Router creates a mini app that holds a group of related routes and middleware. You mount it under a path prefix, which keeps large apps organised by feature.
Explain it simply
A college has one main gate, but each department has its own office handling its own matters. express.Router is the department office. The main app only decides, "Anything starting with /students goes to the students office."
Example
// routes/students.js
const express = require("express");
const router = express.Router();
router.use((req, res, next) => {
console.log("students route hit:", req.method, req.originalUrl);
next();
});
router.get("/", (req, res) => res.json([{ id: 1, name: "Anjali" }]));
router.get("/:id", (req, res) => res.json({ id: req.params.id }));
router.post("/", (req, res) => res.status(201).json(req.body));
module.exports = router;
// app.js
const express = require("express");
const students = require("./routes/students");
const app = express();
app.use(express.json());
app.use("/api/students", students); // paths inside are relative to this prefix
app.listen(3000);Benefits:
- One file per feature: students, courses, payments.
- Middleware can be applied to a whole group, such as
router.use(requireLogin)for admin routes. - Prefixes can be changed in one line, which makes API versioning easy:
app.use("/api/v2/students", studentsV2).
Use express.Router({ mergeParams: true }) if a nested router needs params defined in the parent path.
What to say in the interview
"Router is a modular, mountable group of routes and middleware. I give each feature its own router, mount it with app.use and a prefix, and attach shared middleware to the router."
Common mistakes
- Repeating the prefix inside the router, producing
/api/students/api/students. - Forgetting
mergeParamswhen reading the parent's route parameters.