Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
430 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's what you do:

  • write a middleware your app can use in place of the default express.session middleware
  • in that middleware, based on the 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 request

pseudocode

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...