Search code examples
node.jsexpressmongoosepassport.jsejs

passport middleware does not run


I am using passportJS for authentication. I have called a function setAuthenticatedUser in app.js

app.use(passport.initialize());
app.use(passport.session());
app.use('/', require('./routes'));
app.use(passport.setAuthenticatedUser);

This is my middleware in a file ./config/passport-local.js

passport.setAuthenticatedUser = async function (req, res, next) {
    if (await req.isAuthenticated()) {
        // req.user contains the current signed in user from the session cookie and we are just sending this to the locals for the views
        res.locals.user = req.user;
        // console.log('Locals\' user loaded');
    }
    next();
}

There isn't a error but setAuthenticatedUser doesn't run after calling in app.js. Instead I have to manually call the middleware from each routes

router.get('/', passport.setAuthenticatedUser, homeController.home);
router.get('/route1', passport.setAuthenticatedUser,homeController.route1);
router.get('/route2', passport.setAuthenticatedUser, homeController.route2);
router.get('/route3', passport.setAuthenticatedUser, homeController.route3);
router.get('/route4', passport.setAuthenticatedUser, homeController.route4);

I will be adding a lot more routes in future. What do I do so that I don't have to add the middleware for each get req?

Let me know if you need any more information


Solution

  • Try flipping the order of the last two calls to app.use. Express will call those functions in order as defined.

    I'm assuming your routes defined in ./routes don't call next(), so there's no way for the next set of middlewares (in this case passport.setAuthenticatedUser) to run. So make sure that this call to the Passport function happens before your route handler, or more generally, before any function that won't call next().