Search code examples
node.jssessionexpress-session

NodeJS: session variables shared for all clients (express-session)


I'm using express-session for handling session variables in a NodeJS Application. I use session variables for handling login-authorization, for saving logged user information and other things.

The thing is that this session variables are being shared for all clients, it looks like they are working as NodeJS instance variables instead of session variables for every client. What I want to have is session variables working as they work in PHP.

This application is retrieving all the data from web services in a Laravel Back-End application.

This is my code:

Initializing session:

var sessionHelper = require('./helpers/session-helper');    
var session = require('express-session');
app.use(session({
    secret: config.SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    cookie: {secure: true}
}));
sessionHelper.init(session);
global.SESSION = sessionHelper;

session-helper module:

var _session = null;
module.exports = {
    init: function (session) {
        _session = session;
    },
    has: function (name) {
        return ((_session[name]) ? true : false);
    },
    get: function (name) {
        return _session[name];
    },
    set: function (name, value) {
        _session[name] = value;
    },
    clear: function (name) {
        _session[name] = undefined;
    }
};

Using session variables:

SESSION.set('hotels', response.hotels);
SESSION.get('hotels');

Thanks,


Solution

  • The problem is that you've globally cached a specific instance of session in your helper object. As a general practice, that's not a good idea unless you are very sure about how that object's lifecycle and state are managed.

    The way that express sessions work is that the express middleware maintains a separate instance of session per request. You should be accessing that session typically in the body of a request:

    app.get('/', function(req, res, next) {
        var sess = req.session;
    
        // sess will have values specific to each unique browser session
        console.log('This session has an id of ', sess.id);
    });
    

    If you still feel you want to setup a helper, you can make that available for every request by configuring Express with the use method before your app.get or any other router methods - here is a rough idea how:

    // This should be AFTER the app.use statement for express sessions
    app.use(function (req, res, next) {
        var sessionHelper = require('./helpers/session-helper');
        sessionHelper.init(req.session);
        req.sessionHelper = sessionHelper;
        next();
    })
    

    Now, in any subsequent route handler code, you will find that req.sessionHelper is available for use. This is because you've told Express to first add your helper to the request object for ALL requests. So, this will work:

    app.get('/', function(req, res, next) {
        console.log('Session ID: ', req.sessionHelper.get('id'));
    });
    

    Just remember that you are still responsible for session storage. You need to combine express-sessions with a store (like connect-redis or connect-mongo) in order to persist session-data between restarts. The full list is here: https://github.com/expressjs/session#compatible-session-stores