Once you declare a route, Express inserts the router middleware router middleware stack at this point when you configure the application.
In your case, since you insert .get('/api/test', ...) before inserting the key verification middleware, the middleware of the router gets up and will take precedence (also for the /api/data route, which you declare later) and your key check is never called.
Here are two solutions:
// separate middleware, used for all routes that need checking var keyChecker = function(req, res, next) { ... }; app.get('/api/test', function(req, res) { ... }); app.get('/api/data', keyChecker, function(req, res) { ... }); // or, as an alternative, create a 'catch-all' route between the routes that don't // need to be checked, and the ones that should; this will also match non-existing // routes (like '/api/foobar'), which might or might not be an issue; app.get('/api/test', function(req, res) { ... }); app.all('/api/*', function(req, res, next) { // 'all' means 'all methods' // keychecker code }); app.get('/api/data', function(req, res) { ... });
A third solution would be to explicitly check for /api/test in the key verification tool itself ( req.path === '/api/test' ) and simply call next() if it matches.
source share