Node.js redirect to login if user is not logged in

12,750

You want to write middleware, not a route handler:

app.use(function(req, res, next) {
    if (req.session.user == null){
// if user is not logged-in redirect back to login page //
        res.redirect('/');
    }   else{
        next();
    }
});
Share:
12,750

Related videos on Youtube

Egidi
Author by

Egidi

Updated on June 04, 2022

Comments

  • Egidi
    Egidi almost 2 years

    I am using the node-login module to login on my website. Ok, after the user logs in I render my dashboard.html website:

    app.get('/', function(req, res){
    // check if the user's credentials are saved in a cookie //
        if (req.cookies.user == undefined || req.cookies.pass == undefined){
            res.render(req.locale+'/login', { title: 'Hello - Please Login To Your Account' });
        }   else{
    // attempt automatic login //
            AM.autoLogin(req.cookies.user, req.cookies.pass, function(o){
                if (o != null){
                    req.session.user = o;
                    res.redirect('/home');
                }   else{
                    res.render('/login', { title: 'Hello - Please Login To Your Account' });
                }
            });
        }
    });
    

    After that, all other html websites are linked from within dashboard.html, so there are no other app.get methods called.

    If a user tries to navigate to http://www.example.com/news.html (or any other html page that is not the login page ), if the user is not logged in, I need to redirect him to the login page.

    I first thought somehting like this but I don't know if this is possible:

    app.get('I-don't-know-what-to-insert-here', function(req, res) {
        if (req.session.user == null){
    // if user is not logged-in redirect back to login page //
            res.redirect('/');
        }   else{
            res.redirect('redirect-here-to-the-requested-html-page')  
        }
    });
    

    Regards,

  • Tony
    Tony about 9 years
    your resm next should be res, next. =)
  • Egidi
    Egidi about 9 years
    @SLaks in your solution, when I am inside the if's true code block the res.render or the res.redirect is not working at all. If i console.log something there it works properly. I don't know what's wrong..
  • SLaks
    SLaks about 9 years
    @Egidi: Try console.log(res)
  • atx
    atx over 5 years
    @Egidi there is a missing return statement: return res.redirect('/');
  • kta
    kta about 4 years
    It looks like an infinite loop.