If I enable the session feature of express via app.use(express.session({secret: "12345"}));
the session cookie is set when the user first hits a page.
How can I disable this behavior and decide manually when to create a cookie, for example after a successful login? I am aware that I could just construct a cookie-header manually, but I would like to stay with express.session.
If I enable the session feature of express via app.use(express.session({secret: "12345"}));
the session cookie is set when the user first hits a page.
How can I disable this behavior and decide manually when to create a cookie, for example after a successful login? I am aware that I could just construct a cookie-header manually, but I would like to stay with express.session.
Share Improve this question asked Jan 5, 2014 at 20:17 user3033490user3033490 4- That will be so much tricky and error prone. Could you share with me why you want that? – damphat Commented Jan 5, 2014 at 20:38
- Obviously there is not only a cookie created on the client side, but only resources allocated on the server side.. I thought it would be a good idea to avoid the later if the user never logs in, that is never needs the session. I mean it could be neglected if you dont expect a lot of visitors. I just dont like the idea of my memory or database storage getting "polluted". Is there something I am not seeing? – user3033490 Commented Jan 5, 2014 at 20:45
-
1
Large website will move static data to other domains, so most of requests will not create sessions, for example
static1.yourdomain./image/i1.jpg
will not create session. Inexpress
, you can moveapp.use(express.static(...))
up to the top of other middlewares, so cookie and session middlewares will not run for static request. – damphat Commented Jan 5, 2014 at 20:59 - I am already doing this, it greatly reduces the amout of sessions created that will never be used, but not to zero, so it cannot be called a solution. Can I specify an expiry date for a session entry in the sotrage (not on the client side)? – user3033490 Commented Jan 5, 2014 at 21:06
3 Answers
Reset to default 2Define the session support as middleware, but don't use use
:
var sessions = express.session({
// etc
});
...
app.get('/', function (req, resp) {
// No session
});
app.post('/user', sessions, function (req, resp) {
// Has sessions
I'm not sure if this option existed when this question was originally was posted but I was able to set the saveUninitialized
option as false
to do this.
https://github./expressjs/session#saveuninitialized
Imagine you have a login method... I SUPPOSE you could do like that.
var sessionMW = express.session({secret:"12345"});
function login(req, res, next){
//...
if(success){
return expressMW(req, res, next);
}
}