Bob Dill Bob Dill - 1 month ago 13
Node.js Question

nodejs sessionStore with cloudant app.use inconsistent execution

I'm building a cloudant sessionStore for nodeJS and am stumped by what's going on with the app.use statement. The two following app.use statements vary only in that one has the session called wrapped in a function, however this results in very different behavior.

Example 1:

app.use('/login*', session( {
store: sessionStore,
secret: sessionSecret, resave: false, saveUninitialized: true,
cookie: {secure: true, maxAge:24*60*60*1000},
genid: function (req) {return uuid.v4()}
}));


In the first example, the sessionStore routines are called which create and store a new session ID

Example 2:

app.use('/login*', function () {session( {
store: sessionStore,
secret: sessionSecret, resave: false, saveUninitialized: true,
cookie: {secure: true, maxAge:24*60*60*1000},
genid: function (req) {return uuid.v4()}
})});


In Example 2, wrapping the session statement in a function def results in only calling the sessionStore.on('disconnect') followed by sessionStore.on('connect').

I think I'm missing something really obvious, but am stumped. Two questions:


  1. Why is session() execution different when placed inside an anonymous function?

  2. Is this normal and should my sessionStore.on('connect') be set up to handle this situation?


Answer

In your second example, your anonymous function calls 'session' but doesn't return it.

Express sessions are middleware, so the first usage is correct.

You may also be interested in a pre-built session store for Cloudant: https://www.npmjs.com/package/connect-cloudant

which would make your code:

. . . var app = express(); app.use(session({ store: cloudantStore, secret: 'your secret', cookie: {maxAge:24*60*60*1000} })); app.get('login', function(req, res) { console.log('my session is', req.session); res.send({ok: true}); });

Comments