Node.js Express disable automatic session creation


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.

Define 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

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);
    }
}

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.com/expressjs/session#saveuninitialized