Search code examples
javascriptnode.jsexpressdirectory-structure

passing the express app to the routes files


I'm writing an express 4 api server with no front end code. I chose to structure my project so that the folder structure is based on the business logic of the project rather than doing it based on the type of file (routes, models, etc.)

For instance, my User folder has my userRoutes.js, userModel,js, userApi.js, ...

My main question is actually how should I pass the app into my routes files? My favorite approach was doing global.app and making it global, but I hear that is not best practice. If you have any advice on my business logic structure that would be great too.


Solution

  • Firstly, your file structure sounds over-the-top. If you need that much to split things out cleanly, go for it. But, I have a hunch that you're overdoing it.

    In any case, what I normally do is return middleware from each module. You can give each middleware its own Express router if you want. In the modules:

    const express = require('express');
    
    module.exports = function (config) {
      const router = new express.Router();
    
      router.get('/something', (req, res) => {
        // Code here
      });
    
      return router;
    }
    

    Then in your main application:

    const somethingHandler = require('somethingHandler.js');
    
    app.use(somethingHandler);
    

    This is in-line with how all other Express middleware modules work. This also allows you to namespace modules by path, with your app.use() call in the main app.