title: Express middleware only if route matches later
body: <p>I want to have protected and unprotected routes, and make it so that a request to an undefined route will return a 404 even in the case that the user is unauthenticated. The problem I have is that the authentication middleware runs on all routes except those defined before it, so any undefined routes return an authentication failure instead of a 404. Here's an example of the problem:</p>
  
  <pre><code>var app = express();
  var router = express.Router();
  
  router.get('/', function(req, res) {
    res.send('unprotected route');
  });
  
  // best auth ever
  router.use(function(req, res, next) {
    if(req.body.token) {
      return next();
    }
  
    res.send('auth failed');
  });
  
  router.get('/protected', function(req, res) {
    res.send('protected route');
  });
  
  /// catch 404
  router.use(function(req, res) {
    res.sendStatus(404);
  });
  
  app.use('/', router);
  </code></pre>
  
  <p>In this case, a request without a token to a random route (e.g. /whatever) will return 'auth failed' rather than a 404. How do you resolve this in Express?</p>