Router (Express)
An Express Router is a mini, modular set of routes you can mount on a path. It lets you split a large app's endpoints into separate files (users, posts, auth) and attach them to the main app with app.use().
Node.js
As an Express app grows, keeping every route in one file becomes unwieldy. express.Router() creates a standalone router object that behaves like a mini-app: you define routes and middleware on it, export it, and mount it in the main app under a base path with app.use('/users', usersRouter).
Routers keep related endpoints together and DRY up shared prefixes — every route inside usersRouter is automatically under /users. They can also carry their own middleware that applies only to that group, which is handy for things like requiring authentication on an entire section of the API.
This mirrors how larger frameworks organize routes and parallels Flask's Blueprints. A typical project has a routes/ folder with one router per resource, each mounted in the main server file.
Syntax
const router = express.Router();
app.use("/users", router);Examples
JavaScript
// routes/users.js
const router = require("express").Router();
router.get("/", (req, res) => res.json([{ id: 1 }]));
router.get("/:id", (req, res) => res.json({ id: req.params.id }));
module.exports = router;
// app.js
app.use("/users", require("./routes/users"));