koajs / session

Simple session middleware for koa
MIT License
901 stars 113 forks source link

koa session does not work when used in a middleware app #33

Open mlegenhausen opened 9 years ago

mlegenhausen commented 9 years ago

I am using the vhost middleware with koa-session. Since koa-session 2.0.0 is was possible to use it in a subapp. Since 3.0.0 this does not work anymore. Example:

var session = require('./');
var koa = require('koa');
var compose = require('koa-compose');
var app = koa();

app.keys = ['some secret hurr'];

app.use(session(app));

app.use(function* (next){
  if ('/favicon.ico' == this.path) return;
  var n = this.session.views || 0;
  this.session.views = ++n;
  this.body = n + ' views';
});

var server = koa();
server.use(compose(app.middleware));
server.listen(3000);

console.log('listening on port 3000');
jonathanong commented 9 years ago

this is because the session is attached to the app's prototype and compose does not keep/inherit the prototype.

mlegenhausen commented 9 years ago

So this is a bug or a feature?

jonathanong commented 9 years ago

neither and both. it would be a feature to some people and a bug to others.

personally, i don't ever recommend combining multiple apps like that. i would actually vhost in a layer outside of koa.

chrisveness commented 9 years ago

I am also having problems with koa-session (in fact, koa-flash) which I suspect may be related to this.

I am using virtual host apps as per https://github.com/koajs/examples/tree/master/vhost.

Is it possible to use koa-session with this configuration? If so, could you give me a pointer as to how it should be done? If not, have you any other suggestions?

Thanks.

mlegenhausen commented 9 years ago

And also some recommendations how you would handle applications with different subdomains that run in a PaaS environments without nginx or haproxy. Would you recomment node-http-proxy or simply adding session to the root app?

nltesown commented 6 years ago

So, how does this look 3 years later (and with Koa2)? Like @chrisveness, I'm in the virtual host apps scenario and I need sessions to be managed on a per app basis.

How did those concerned solve the issue? Is there a recommended solution?

chrisveness commented 6 years ago

I don't recall any longer what the issue turned out to be, but I am successfully using koa-session on a per-app basis with Koa v2: e.g. https://github.com/chrisveness/koa-sample-web-app-api-mysql/blob/master/app.js (don't know about a 'recommended' solution!).

Things are a bit more complex if you want to have session variables common to multiple sub-apps: you would have to use the domain option, setting it to the super-domain common to your sub-domains. Bear in mind, though, that for testing, cookies on localhost can be problematic.