Jason Martocci Jason Martocci - 5 months ago 14
SQL Question

Redirect if session is not available node.js

I am trying to write code for my route that if the session.user_id is undefined redirect back to the home page. For some reason the redirect doesnt execute and the mysql condition is fired and it crashes the server because the session.user_id is undefined and it cant load the game without that data.

Is there a way to use a universal redirect on all routes that if session is not available redirect back to login?

router.get('/game', function(req,res) {

console.log(req.session.user_id);

if (req.session.user_id === "undefined") {

res.redirect('/');

}else {

var condition = 'userId = ' + req.session.user_id;

projectX.allGameData(condition, function(data){

var hbsObject = {heroes : data, logged_in: req.session.logged_in, isUser: req.session.isUser, isAdmin: req.session.isAdmin}

res.render('game', hbsObject);

});

};

});

Answer

You should either use: if (req.session.user_id === undefined)

OR if ( typeof req.session.user_id === "undefined")

Apart from that, it's usually better to have a middleware function that checks for user session. This way, you can just insert the call to this middleware in all your routes, which require the user to be logged in:

router.get('/game', checkUserSession, function(req,res) {
  // Your code here
});

function checkUserSession( req, res, next )
{
    if( req.session.user_id )
    {
        next();
    }
    else
    {
        res.redirect('/homepage');
    }
}//checkUserSession()