I have a situation where an app can be accessed from multiple different domains. For instance, foo.com and bar.com could both in theory point to my app. Additionally, their subdomains can also point to my app, so for instance red.foo.com and blue.foo.com. I'm using Express cookie sessions, and my initialization code for the session looks like that:
app.use(express.session({
secret: "secret",
cookie: {
domain: ".foo.com"
},
store: new MongoStore({
db: db
})
}));
That works well for when users go through foo.com or any of it's subdomains, but bar.com won't work. I need to have both at once. Ideally, I would set it to a different domain per request, but I'm not sure how I would do that. My requests are highly asynchronous and if I just set it for the whole app at every request, I fear it might not work when two calls come in at once.
Is this at all possible? Does anyone have any ideas to solve this?
Here's what you do:
host
request header instatiate and configure on instance of the express session middleware per domain, and then actually execute the middleware function appropriate for this requestpseudocode
var mwCache = Object.create(null);
function virtualHostSession(req, res, next) {
var host = req.get('host'); //maybe normalize with toLowerCase etc
var hostSession = mwCache[host];
if (!hostSession) {
hostSession = mwCache[host] = express.session(..config for this host...);
}
hostSession(req, res, next);
//don't need to call next since hostSession will do it for you
}
app.use(virtualHostSession);
My requests are highly asynchronous and if I just set it for the whole app at every request, I fear it might not work when two calls come in at once.
Absolutely you cannot do that. It will be utterly incorrect.