Express app - Execute function on many but not all requests
<p>What is the best way to call a function on many but not all requests in a node express app? (An example would be a function which checks if the user is currently logged in)</p>

<p>What I did is to define a module exporting a <code>checkLogin(...)</code> function and to call this function on each corresponding api-request. E.g.:</p>

<p>Module auth:</p>

<pre><code>module.exports = {
    checkLogin: function(req, res, next) {
        if (req.session.hasOwnProperty('user')) {
            //if the user is logged in we pass through
            next();
        } else if (req.cookies.user == undefined || req.cookies.pass == undefined) {
            res.render('login', { title: 'Login' });
        } else {
            User.checkLogin(req.cookies.user, req.cookies.pass, true, function(o) {
                if (o != null) {
                    req.session.user = o;
                    next();
                } else {
                    res.render('login', { title: 'Login' });
                    return;
                }
            });
        }
    }
};
</code></pre>

<p>Routes for /index:</p>

<pre><code>//...
var auth = require('../middlewares/auth.js');
//...
    router.get('/index', auth.checkLogin, function(req, res) {

        //if we passed the auth.checkLogin step we render the index page
        res.render('index', {
            title: 'Index',
            udata: req.session.user
        });

    });
</code></pre>

<p>In another route file:</p>

<pre><code>//...
var auth = require('../middlewares/auth.js');
//...
        router.get('/user/someAPICall', auth.checkLogin, function(req, res) {
           ...
        });
</code></pre>

<p>Is this the way to go or are there better ways to do that? I could define a middleware function which I could include using <code>app.use(function(){..})</code> in each route. The problem is that every request for this route would go through this function which is not what I want.</p>