Is it common practice to have a file for each type of route?
Yes, Express like other helpful libraries for request handling works best if set in a modular way, not just because certain files can be reused, but it also makes it easier to read while Express methods make the functionality quite clear in their purpose. As we progress through the lessons we will notice that even though there is no specific (“required” by Express) way to structure our App, it makes it easy to scale if we keep certain parts of our code in their own files and therefore it has become a common practice between teams and developers, for example, having a router file that specifies all routes and depending on the main route, it will use the respective file that handles the request to that route, for example:
const router = require('express').Router(); router.use('/tasks', require('./controllers/todolist')); router.use('/api', require('./controllers/api')); router.get('/', (req, res) => res.render('index')); module.exports = router;
In this router file, we request the router method and we specify that it will use the specific files for the respective routes, so every time the
/tasks route is hit, it will be directed and handled in the file
todolist.js found in the controllers/ directory.
For now, we will go step by step, starting to keep the router in our
app.js and have our individual files for each route.