ExpressJS Tips: Cleaner Routes

When our application become larger, it's becoming harder to maintain a huge list of routing in one file. I found that it's easier to split the routes into each own section.
Here's how i do that

Example Directory Layout

app.js
controllers
routes
--- index.js
--- posts.js
--- users.js


Example Code

/routes/index.js
const router = require('express').Router();

router.use('/posts',require('./posts.route'));
router.use('/users',require('./users.route'));

module.exports = router


/routes/users.route.js
const router = require("express").Router();
const UsersController = require("../controllers/user.controller");
router.get("/", UserController.index);
module.exports = router;


app.js
//import all routes
app.use("/api/v1", require("./src/routes/index"));


Example Endpoint Results
GET /api/v1/users
GET /api/v1/posts

That's all!

Comments