Search code examples
node.jsexpressorganization

Move routes into files in Express.js


Say I have some routes (I have a lot more, but this should explain):

router.post('/post');
router.get('/post/:id');
router.get('/posts/:page?');
router.get('/search');

For the /post ones I know I could do something like

app.use('/post', postRoutes)

Where postRoutes is the actual post routes in another file. However, I'd like to group all post related routes into a postRoutes component (so /post and /posts), search into a search component and so on. Is there a way to do something like

router.use(postRoutes); // includes routes 1-3 above
router.use(searchRoutes); // only the 4th route above

And so on? That would let me keep the top level file much cleaner.


Solution

  • The problem was I was thinking about this wrong. First off, don't use singular and plural. It makes it a headache and also makes it hard for people to remember the API.

    Once I used all plural I had a setup like this in my index.js file:

    // The API routes all start with /api and we pass app here so we can have some
    // sub routes inside of api
    app.use('/api', require('./app/api')(app));
    

    And then in my api/index.js

    var express = require('express');
    var router = express.Router({ mergeParams: true });
    
    var routeInit = function (app) {
      app.use('sessions', require('./sessions')(router));
      app.use('users', require('./users')(router));
      return router;
    };
    
    module.exports = routeInit;
    

    You can see that I'm passing the router manually each time. Then finally:

    var routeInit = function (router) {
      router.post('/blah', function (req, res, next) {
        // Do stuff
      });
    
      return router;
    };
    
    module.exports = routeInit;
    

    This allowed me to nest routes infinitely deep.