node.jssessionexpress

nodejs express static routes creating multiple sessions


I am using Nodejs and Express. I have a routes.js file defining all my routes. When I try to use req.session.regenerate(), express creates multiple sessions including one each for static file requests as well.

Whats confusing is req.session.regenerate() is within app.get('/' route and it seems from the console.log it gets called only once. But somehow when I look at the mongodb session collection, there are multiple sessions created for one page request.

basically what I am trying to do is when the login page is requested I want to create a new session so that express does not re-use previous session's cookie.

Any pointers?

routes.js

exports = module.exports = function(app, passport) {

//When I uncomment this line, it shows me the number of times a request is made.
//app.all('*', function(req, res, next){console.log('Request made to server'); next();});

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

    if (req.isAuthenticated()){
        res.redirect('./home');
    }else{

       req.session.regenerate(function(err) {
            console.log('Regenerated');
       })

        res.render('./login')
    }
});

Solution

  • Put your express session middleware after your express.static() middleware.