M3NTA7 M3NTA7 - 6 months ago 27
Node.js Question

client-sessions nodejs / Express - error: Cannot set property 'mydata' of undefined

I'm trying to use the client-sessions middleware in nodejs / Express and I get the following error:

Cannot set property 'mydata' of undefined.


I've also looked at this post, but could not find additional clues as to why I may be getting the error. node-js-client-sessions-not-creating-req-session

var bodyParser = require('body-parser');
const express = require('express');

const app = express();
const clientSessions = require("client-sessions");

var urlencodedParser = bodyParser.urlencoded({ extended: false });
var router = express.Router();

app.use(clientSessions({
cookieName: 'mydata', // cookie name dictates the key name added to the request object
secret: 'longsecretkeyorwhatever', // should be a large unguessable string
duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms
activeDuration: 1000 * 60 * 5 // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds
}));

/* Form POST handler */
router.post('/', urlencodedParser, function(req, res) {
if (!req.body) return res.sendStatus(400);

if(req.body.firstName){
req.session_state.mydata = req.body.mydata;
}
})

Answer

The documentation of client-sessions explains:

cookie name dictates the key name added to the request object

Since you're setting firstName as cookie name, the session object is available as req.firstName:

req.firstName.mydata = req.body.mydata