Search code examples
javascriptnode.jsmongoosepassport.jspassport-local-mongoose

How can i redirect no-logged user from all urls? PassportJs


I'm doing a web app with nodeJS and for the authentication I'm using PassportJs with passport-local-mongoose.

I make this snippet for the root route to check if the user is logged in

 app.get('/', function(req, res){

    if(req.isAuthenticated()){


    List.find({}, function(err, results){

        if(!err){
            res.render('home');
        }});   

    }else{
        res.redirect('/login');
    }
});

so my question is: there's a way to redirect the user to the login page if they are non-logged, from all URLs without specifying it in all the routes get.


Solution

  • Express comes up with middlewares. Basically, a request pass through all middlewares that match its path and http method. You can do whatever you want in a middleware, then either send a response or pass the request to the next middleware.

    // All get requests
    app.get('*', function(req, res, next){
        // If not authenticated
        if(!req.isAuthenticated()) {
            res.redirect('/login');
        }
    
        // Else,  go to the next middleware
        next();
    }
    
    // Real business here
    app.get('/', function(req, res){
        List.find({}, function(err, results){
            if(!err){
                res.render('home');
            }});   
        }
    });
    

    You can read more here : https://expressjs.com/en/guide/using-middleware.html