top of page

How to add multiple routers in a node application without using app.use() for each router ?

Updated: Sep 18, 2021

In node.js, when we have multiple Express.Router written in a separate file to enhance modularization we need to import each route file into the application server file and add lots of app.use() statements. Now, if we add a new router we need to remember to add that too in the file where the application server is written.


The code with multiple routers written in separate files looks like this. Let's assume there is a routes folder where the routes are defined for user and order handling separately.


In routes/user.js file

const router = require('express').Router();

module.exports = function () {
router.get('/user/:id', (request, response) => {
 response.send('Hello World From User Get ' + request.params.id);
});
router.post('/user/:id', function(request, response) {
 response.send('Hello World From User Post ' + request.params.id);
});
return router;
}

in routes/order.js file

const router = require('express').Router();

module.exports = function () {
router.get('/order/:id', (request, response) => {
 response.send('Hello World From Order Get ' + request.params.id);
});
router.post('/order/:id', function(request, response) {
 response.send('Hello World From Order Post ' + request.params.id);
});
return router;
}

In app.js file

const express = require('express');
const app = express();
const port = 5000;
const userRouter = require('./routes/user.js')();
const orderRouter = require('./routes/order.js')();

app.use(userRouter);
app.use(orderRouter);
app.listen(port, () => {
  console.log(`My app listening at http://localhost:${port}`);
});

Instead of adding app.use() each time for a router that handles a specific route file we can write a code snippet that can read all route files from the routes directory and add them to the app.use() .


In app.js file

const express = require('express');
const app = express();
const port = 5000;


const fs = require('fs');
/* backslash for windows, in unix it would be forward slash */
const routes_directory = require('path').resolve(__dirname) + '\\routes\\'; 

fs.readdirSync(routes_directory).forEach(route_file => {
  try {
    app.use('/', require(routes_directory + route_file)());
  } catch (error) {
    console.log(`Encountered Error initializing routes from ${route_file}`);
    console.log(error);
  }
});

app.listen(port, () => {
  console.log(`My app listening at http://localhost:${port}`);
});

This is how we can avoid manually coding app.use() for each router in the node.js application





5,160 views0 comments

Recent Posts

See All
bottom of page