connect-mongo creating new session every second

柔情痞子 提交于 2019-12-06 12:37:39

If you are using express-session >= 1.10.0 and don't want to resave all the session on database every single time that the user refresh the page, you can lazy update the session, by limiting a period of time. Because you're are using a newer version of connect-mongo and an older version of express im not 100% sure,but i think this is because of either the cookie or the Uninitialized session.

// Configuring sessions
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
app.use(session({
    secret: 'JohnSecret',
    saveUninitialized: false, // don't create session until something stored
    resave: false, //don't save session if unmodified
    store: new MongoStore({
      url: 'mongodb://localhost/John',
      autoRemove: 'interval',
      autoRemoveInterval: 10 // In minutes. Default
    })
}));

Okay, it is the issue with HAProxy continuously checking the backend server to see that its up and working. In doing so it is creating a session a second and cluttering my database. So here is my (dirty) fix:

  1. Create an api /ping that handles HAProxy's httpchk by destroying each session

    app.get('/ping', function(req, res){ req.session.destroy(); res.send(200); });

  2. Configure haproxy/conf to change option httpchk GET / to option httpchk GET /ping

  3. Restart HAProxy cartridge using RHC rhc cartridge-restart --cartridge haproxy

I just dealt with this issue as well, and for me it turned out to be resulting from my AWS healthcheck. Every healthcheck ping created and stored a new session. I fixed this by bypassing store whenever the request is a healthcheck:

app.use(function(req, res, done) {
  var isHealthcheck = req.url.indexOf('healthcheck') > -1;
  session({
    secret: config.secrets.session,
    saveUninitialized: true,
    resave: false,
    store: isHealthcheck || new MongoStore({
      mongooseConnection: mongoose.connection,
      db: 'myDb'
    })
  })(req, res, done);
});

So, when isHealthcheck is true, it passes store nothing. When it's not, it does a normal store of the session. The key part here is isHealthCheck ||.

Hope this helps someone!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!