Tuesday, 14 May 2019

How can I organize my Express Router routes better?

I have been working with Node for a while but have never loved my solution for my routes (the solution I learned from many tutorials). I feel like there has to be a more organized way to do this.​I'll use the blog I am building as an example. My index.js (entry point) is something like this:const express = require('express');const app = express();// Import Routesconst userRoutes = require('./routes/userRoutes');const postRoutes = require('./routes/postRoutes');​app.use('/users', userRoutes);app.use('/posts', postRoutes);​// Start appconst PORT = process.env.PORT || 3000;app.listen(PORT, () => {console.log("App listening on port", PORT);});​As my apps grow or have requirements for different routes like userRoutes, postRoutes, adminRoutes, etc, that list from the // Import Routes begins to grow and get a bit out of control for my index.js file. Is there a good way to just import a single file/route that encompasses and exports all of my routes so I don't have to make my index file so messy?​Something like:// Import Routesconst allRoutes = require('./routes');​app.use('/', allRoutes);​Where an index.js inside the ./routes directory would be doing the importing/exporting of the potential many routes? I've tried to find examples of this being done but can't find anything useful. I've tried Googling "organizing express router routes" and things like that but nothing is steering me in a cleaner direction (that I have found). Any tips for cleaning this up? Or is this the typical way of handling a bunch of routes?

Submitted May 14, 2019 at 05:18PM by HellaDev

No comments:

Post a Comment