Remove route mappings in NodeJS Express

This removes app.use middlewares and/or app.VERB (get/post) routes. Tested on [email protected]

var routes = app._router.stack;
routes.forEach(removeMiddlewares);
function removeMiddlewares(route, i, routes) {
    switch (route.handle.name) {
        case 'yourMiddlewareFunctionName':
        case 'yourRouteFunctionName':
            routes.splice(i, 1);
    }
    if (route.route)
        route.route.stack.forEach(removeMiddlewares);
}

Note that it requires that the middleware/route functions have names:

app.use(function yourMiddlewareFunctionName(req, res, next) {
    ...          ^ named function
});

It won’t work if the function is anonymous:

app.get('/path', function(req, res, next) {
    ...          ^ anonymous function, won't work                    
});

Leave a Comment