Search code examples
node.jsexpressroutes

How to organize routes in Nodejs Express app


I am working on Nodejs/Express app.I used express-generator to create basic structure. For now a specify all routes in the app.js file

var indexRouter = require('./routes/index');
var router1Router = require('./routes/router1');
var router2Router = require('./routes/router2');
......
app.use('/', indexRouter);
app.use('/router1', router1Router);
app.use('/router2', router2Router);

Everything is works as expected. However I came across a suggestion to have routes.js file in the root folder of the application and

Require all routes in this and then require this file in app.js

However, I am having hard time to figure out how to set it up properly. Any suggestions will be greatly appreaciated. Thanks in advance.


Solution

  • It is a good idea to keep the main file short and simple.

    I put all my routes to the routes folder.

        |-- app.js
        |-- routes
        |   |-- index.js
        |   |-- router1.js
        |   |-- router2.js
        |-- startup
        |   |-- routes.js
    

    In the startup/routes.js file I import all the routes like this:

    const express = require("express");
    var indexRouter = require("../routes/index");
    var router1Router = require("../routes/router1");
    var router2Router = require("../routes/router2");
    
    module.exports = function(app) {
      app.use(express.json());
    
      app.use("/", indexRouter);
      app.use("/router1", router1Router);
      app.use("/router2", router2Router);
    };
    

    And App.js I only import startup/routes.js like this:

    const express = require("express");
    const app = express();
    
    require("./startup/routes")(app);
    
    const port = process.env.PORT || 3000;
    
    app.listen(port, () => console.log(`Listening on port ${port}...`));
    

    In this way, when we want to add another route to our app, we add it to the startup/routes.js, without needing to make change to the App.js file, which keeps our App.js clean and short.

    You can also add other files (for example database connect) to the startup folder later when required, and import them to the App.js.