title: How to setup an authentication middleware in Express.js
body: <p>I have set up a web application with some internal pages requiring a login. I used Node with Express.js to set up the server and controlling the routes and authentication works fine.</p>
  
  <p>I came up to a @zanko suggestion in a <a href="https://stackoverflow.com/questions/47513553/bypassed-authentication-in-route-handling?noredirect=1#comment81986582_47513553">question related to the same application</a> to avoid the replication of the authentication code in the route of every page, like is now.</p>
  
  <p>At the moment my app.js looks like this (the following is an excerpt):</p>
  
  <pre><code>var session = require('express-session');
  //use sessions for tracking logins
  app.use(session({
    secret: 'mercuia',
    resave: true,
    saveUninitialized: false,
    store: new MongoStore({
    mongooseConnection: db
  })
  }));
  
  // serve static files from template
  app.use(express.static(__dirname + '/public'));
  
  // include routes
  var routes = require('./routes/router');
  app.use('/', routes);
  
  // catch 404 and forward to error handler
  app.use(function (req, res, next) {
    var err = new Error('File Not Found');
    err.status = 404;
    next(err);
  });
  
  // error handler
  // define as the last app.use callback
  app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.send(err.message);
  });
  </code></pre>
  
  <p>and my authentication method (in routes.js) looks like this (in the example, for the route /clientPage):</p>
  
  <pre><code>// GET route after registering
  router.get('/clientPage', function (req, res, next) {
    User.findById(req.session.userId)
      .exec(function (error, user) {
        if (error) {
          return next(error);
        } else {      
          if (user === null) {     
            var err = new Error('Not authorized! Go back!');
            err.status = 400;
            return next(err);
          } else {
            return res.sendFile(path.join(__dirname + '/../views/clientPage.html'));
          }
        }
      });
  });
  </code></pre>
  
  <p>How can I write an authentication middleware instead (using the same logic) and call it for all and only the requiring routes?</p>