Structuring Routes with express.Router()
10 min read
Structuring Routes with express.Router()
As your API grows, keeping all routes in a single file becomes unmanageable. express.Router() creates a mini-application that has its own middleware and routing, and is then mounted onto the main app at a path prefix.
js
// src/routes/users.ts
import { Router } from "express";
const router = Router();
router.get("/", (req, res) => {
res.json({ message: "list users" });
});
router.post("/", (req, res) => {
res.status(201).json({ message: "create user" });
});
router.get("/:id", (req, res) => {
res.json({ id: req.params.id });
});
export default router;js
// src/app.ts
import express from "express";
import usersRouter from "./routes/users";
const app = express();
app.use(express.json());
app.use("/users", usersRouter);
export default app;Recommended Project Structure
src/app.ts— create and configure the Express appsrc/index.ts— callapp.listen()src/routes/— one file per resource routersrc/controllers/— handler functions imported by routerssrc/middleware/— shared middleware (auth, validation, logging)src/lib/orsrc/services/— business logic and DB access
Mount all API routers under a version prefix like /api/v1 from the start. It costs nothing now and makes non-breaking API evolution far easier later.
Ready to test yourself?
Practice Express— quiz & coding exercises