Search code examples
node.jsexpressroutesnested-routesmodule-export

How to use nested-subfloders routing in nodejs express application?


I am working on a node project using express. I have some folders in the routes folder which include several .js files having routes. I want to keep the structure this way to keep my code neat & clear. How to require the routes in app.js file neatly?

  1. Seeing this, https://github.com/searsaw/express-routing-example/blob/master/app.js, I tried simply :
const routes = require('./routes');
app.use('/', routes);

but it doesn't work & brings my routes into action.

  1. Seeing this, I tried the require-dir method too, but it doesn't work as well. Nodejs Express: Routes in separete files

My folder structure is like :

-routes
    -admin
        -login.js
        -CRUD_event.js
        -CRUD_venue.js
     -client
         -login.js
         -CR_event.js
         -CR_venue.js

I don't want to mess my app.js file, I know all the routes can be required separately but that would be quite of just requiring code in app.js. I want to keep the route directory structure & require them in app.js in the most optimized way possible.


Solution

  • I found where I am going wrong. This https://github.com/searsaw/express-routing-example/blob/master/app.js actually explains it all. In the routes folder, there is an index.js file requiring & using all other routes & then it is exported. It completely solves the problem.