express.Router() creates a mini, self-contained Express instance you can attach routes and
middleware to, then mount on the main app under a path prefix.
Syntax
express.Router([options])
options can include caseSensitive, mergeParams, and strict.
Basic example
const express = require("express");
const app = express();
const PORT = 4500;
const authorRouter = express.Router();
authorRouter.get("/", (req, res) => {
res.send("Authors Home");
});
app.use("/authors", authorRouter);
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
A GET request to /authors returns "Authors Home".
Multiple routers
const authorRouter = express.Router();
const editorRouter = express.Router();
const readerRouter = express.Router();
authorRouter.get("/", (req, res) => res.send("Author Router Working"));
editorRouter.get("/", (req, res) => res.send("Editor Router Working"));
readerRouter.get("/", (req, res) => res.send("Reader Router Working"));
app.use("/author", authorRouter);
app.use("/editor", editorRouter);
app.use("/reader", readerRouter);
Each router handles its own path prefix independently, keeping route files small and focused.
Why use it
- Groups related routes by feature.
- Keeps large apps organized into modules.
- Lets you attach middleware to just one group of routes.
- Keeps individual route files short and readable.