Search code examples
node.jsexpresscookie-session

node.js express cookie-session session id undefined


I'm using node.js with express and the cookie-session library, and in request handlers, req.session.id is undefined - could anyone provide suggestions on creating and using a session id with cookie session or any cookie based session library within express?

Edit: My cookie-sesssion is set up as follows

var session = require('cookie-session');    
app.use(session({
            key: 'express.sid',
            secret: secretKey,
            saveUninitialized: true,
            resave: true,
            cookie: {
                maxAge: 1000 * 60 * 60 * 72,
                httpOnly: true,
                secure: true
            }
        }));

then wherever I have an endpoint, eg.

router.get('/api/something', function (req, res) {

req.session.id and req.sessionID are undefined. If I use a normal express session they're populated.


Solution

  • I've got around this for now by setting

    req.session.id = req.session.id || uuid.v4() 
    

    This code is only done in one location, within my logger, so is a simple tweak, however I feel it must be something that other cookie-session users must have tackled at some point! I'll set this as the answer for now, hopefully a better answer will supersede it.