John John - 3 months ago 20
Node.js Question

Node js too many redirect using middleware redirect

In my Node.js application (I'm using express 4.x) I want to check if the user is logged. If the user isn't logged I want to redirect to my login page. Then I do that in the middleware like this :

Server.js

app.use(function (req, res, next) {

// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();

// if they aren't redirect them to the home page
res.redirect('/login');
});


Login route

// Login page
app.get('/login', function(req, res){
res.render('pages/login', {
error : req.flash('loginError'),
info : req.flash('info'),
success : req.flash('success')
});
});


But when I add this code in my middleware, the login page is called more than 30 times... And my browser says
Too many redirect
.

Do you know why my login page is called a lot ?

Answer

You catch in infinite loop because if the requested path is login even so redirect to login again

app.use(function (req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    if(req.route.path !== '/login')
      res.redirect('/login');
    next();
});