Search code examples
node.jsexpressurl-routingexpress-session

session handling in expressjs with router


I'm using expressJS, and I'm a bit confused about sessions. I have 1 single expressJS server, which is reachable from different URLs. Depending on where the connection is coming frmo (which URL is opened), a different database is used to provide the responses. And I can see that the sessions are conflicting.

My assumption is that I should be setting different cookie names, based on the URL of the request, but it seems I can't specify a function within the session config.

Any ideas?

var app = express();
var session = require('express-session');

var router = express.Router();

app.use('/a_route', router);
app.use('/b_route', router);

router.use(session({
    genid: function(req) {
    return require('crypto').randomBytes(48).toString('hex'); // use UUIDs for session IDs
    },
    secret: 'JollynakAjollynakAjollynakApamPam',
    resave: false,
    saveUninitialized: false,
    name: **THIS SHOULD BE DYNAMIC BASED ON URL???**
}));

EDIT

//declare session variable
var sess ="";


router.post('/login', function (req, res, next) {

    sess = req.session;

    var uname = req.body.username;
    var pwd = req.body.password;
    var authResult = null;

    sess.username = uname;
    sess.instance = req.baseUrl.replace('/', '');
})

And an example AJAX call

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

    service.getCaps(sess.instance, function (response) {
        res.send(JSON.stringify(response));
    });
});

Solution

  • Your cookies aren't necessarily tied to your databases. All of your routes share one cookie store. "Name" refers to the name of your session cookie and this applies to all of your routes (that's why express-session is middleware called in app.use). In general you will only have one session per express app. If you really want to distinguish these with multiple session stores, you'll want to create multiple express apps to handle your routes.

    In your situation, it looks like you should really be using two entirely different routers with two entirely separate sets of URLS. You'll have some duplicate code, but since you're dealing with two separate databases, two different "sessions", and two different URLs it makes sense to separate them. Then you can have unique session variables for each route (e.g. req.session.aLogin and req.session.bLogin);

    var routerA = express.Router();
    var routerB = express.Router();
    
    app.use('/a_route', routerA);
    app.use('/b_route', routerB);
    

    Another approach is just to juggle separate session variables within your routes.

    router.post('/login', function (req, res) {
       req.session[req.baseUrl + 'auth'] = true;
    });
    
    router.get('/something', function (req, res) {
       if (req.session[req.baseUrl + 'auth'] { //User is authenticated for this particular database
           //Rest of your code
       }
    });