Search code examples
node.jsexpressmiddleware

ExpressJS - Middleware Too Many Redirects


I am trying to use two middleware with my /app routes that checks for user authentication and then the status of their account. I have both middleware in place, but I am running into an endless redirect in instances where my req.session.accountStatus does not equal the conditions I have provided it. In general, I am trying to force the user to only have access to the page being redirected to. Am I using middleware in the wrong way? Is there a better approach?

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()){
        return next();
    }
    res.redirect('/login');
}

function accountStatus(req, res, next) {
    if(req.session.accountStatus == "active" || req.session.accountStatus == "trialing"){
        return next();
    } else {
        //Endless loop. Need to fix
        res.redirect('/app/settings/billing');
    }
}

router.use(require('./site-routes'));
router.use('/app', isLoggedIn, accountStatus, require('./app-routes'));

Solution

  • It's probably easier to move the middleware to app-router.js.

    So your main file would only do this:

    router.use('/app', require('./app-routes'));
    

    In app-routes.js, you first add the route for the URL that should be "open";

    router.get('/settings/billing', ...);
    

    Followed by the restrictive middleware:

    router.use(isLoggedIn, accountStatus);
    

    Followed by the rest of the routes.

    That way, any requests for /app/settings/billing don't get passed through the middleware at all, and won't cause a redirect loop.

    If isLoggedIn is mandatory for any route that starts with /app, you can use it in a similar way:

    router.use(isLoggedIn);
    router.get('/settings/billing', ...);
    router.use(accountStatus);
    router.get(...);