Node+Passport.js + Sessions + multiple servers

有些话、适合烂在心里 提交于 2019-12-04 12:54:58

OK, So basically what I was looking for (not sure it would be the same answer for everyone else) was a way to store session data between loadbalanced instances without making a DB call for every page view, which seems excessive to me, since I just need to keep the user signed in to Google/FB.

It seems that the answer I was looking for was the cookie-session middleware https://github.com/expressjs/cookie-session

This needs to replace the default express.session mechanism which uses MemoryStore. BTW MemoryStore itself gives you a warning when run that it will not scale past a single process, and also that it may cause a memory leak.

Which if I understand correctly is serializing the session data itself into the session cookie (encrypted) instead of just using a session ID in the session cookie. This seems perfect to me. Obviously I don't expect it to work if you have a lot of session data, since a cookie is limited in size. In my case, I just needed the name, ID and avatar url, so I think this will suffice. Thanks for everyone who helped.

You need to store your session data in a 'global' area, that is accessible to all your servers. This could be redis or another DB.

Take the example from MEAN.JS. Here they use express-session with a MongoDB storage container (since they are a MEAN stack ; ), via connect-mongo. Their project is super easy to set up, if just for an example.

Code while setting up express is like this:

//top of file
var session = require( 'express-session' )
    mongoStore = require( 'connect-mongo' )( {
        session: session
    } );

//...later in setup

// Express MongoDB session storage
app.use( session( {
    saveUninitialized: true,
    resave: true,
    secret: config.sessionSecret,
    store: new mongoStore( {
        db: db.connection.db,
        collection: config.sessionCollection
    } )
} ) );

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