0

I have a 4 year old Express project running in production and using Express 4.14. Various developers have kept on adding new features but some old code also remains inside. Is there a way to find unused code- code which is not getting used in a production application ?.

I would like to start by identifying routes that are not being called. We do use logs and logs are ingested in Kibana. We also use APM with Kibana.

jmls
  • 2,879
  • 4
  • 34
  • 58
DrEarnest
  • 853
  • 2
  • 13
  • 27

1 Answers1

2

Since you log data you can create simple middleware to log every request to your application. After a while (days or weeks, depending on how sure you will feel about this process) you can collect and parse logs to get all requested routes. Then compare requested routes with all routes available in your application and delete unused ones.

The middleware can be as simple as:

// runs for every request
app.use('/', function (req, res, next) {
    console.log(`Received request: ${req.method} ${req.path}`);
    next();
});

To get all routes registered in your application use this development-only code (inspired by this answer):

console.log(app._router.stack.forEach(middleware => {
    if (middleware.route) {
        console.log(`${middleware.route.stack[0].method} ${middleware.route.path}`);
    } else if (middleware.name === 'router') {
        middleware.handle.stack.forEach(route => {
            if (route.route) {
                console.log(`${route.route.stack[0].method} ${route.route.path}`);
            }
        });
    }
}));
macborowy
  • 1,474
  • 10
  • 13