title: Express.js middleware executing for a route defined above it
body: <p>From what I have read <a href="https://scotch.io/tutorials/learn-to-use-the-new-router-in-expressjs-4" rel="nofollow noreferrer">here</a> and <a href="https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens" rel="nofollow noreferrer">here</a>, the order in which you place your middleware function matters, as you can have certain routes not go through the middleware function if it is placed before the route, and the routes which are placed after will go through this middleware function.</p>
  
  <p>I am seeing mixed results as my dev environment is not respecting this and my prod environment is. The code is exactly the same.</p>
  
  <p>What I am trying to do is have my login route not be protected by a token checker middleware function and have the rest of my routes protected by a token.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>routes.get('/login', function(req, res) {
      // login user, get token
  });
  
  routes.use(function(req, res, next) {
      // check header or url parameters or post parameters for token
      var token = req.headers['access-token'];
      // decode token
      if (token) {
          // validate token
      }
      else if (req.method === 'OPTIONS') {
          next();
      }
      else {
          // if there is no token
          // return an error
          return res.status(403).send({
              success: false,
              message: 'No token provided.'
          });
      }
  });
  
  routes.get('/query/:keywords', function(req, res) {
      console.log(req.params.keywords);
      // execute query
  });
  
  app.use('/', routes);
  </code></pre>
  
  <p>the <code>/query</code> route is the only one that should have to go through the token middleware function correct? Right now I am getting the <code>/login</code> route also going through the token middleware function, which doesn't make sense as I shouldn't need to have a token to login.</p>
  
  <p>Better yet, if there is a way to target which routes I want protected and which routes I do not want protected, this seems better than having to rely on an "order" of where the middleware function is placed.</p>