I was experimenting with NodeJs with Session. I followed code from many sites. Simplest one I would like to mentioned is Sample NodeJS Code for session management with Redis
Rest of the forums found similar to it. Issue I am facing is when I am not using the redis as session store everything work fine. Below changes in code for swithcing from redis session to In memory session.
app.use(session({
secret: 'secret$%^134',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // if true only transmit cookie over https
httpOnly: false, // if true prevent client side JS from reading the cookie
maxAge: 1000 * 60 * 10 // session max age in miliseconds
}
}))
But as I put the Redis store back in sample, I start getting exception Client is closed. Code for enabling the Redis session store is
const RedisStore = connectRedis(session)
//Configure redis client
const redisClient = redis.createClient({
host: 'localhost',
port: 6379
})
redisClient.on('error', function (err) {
console.log('Could not establish a connection with redis. ' err);
});
redisClient.on('connect', function (err) {
console.log('Connected to redis successfully');
});
//Configure session middleware
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: 'secret$%^134',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // if true only transmit cookie over https
httpOnly: false, // if true prevent client side JS from reading the cookie
maxAge: 1000 * 60 * 10 // session max age in miliseconds
}
}));
CodePudding user response:
After lots of reading, I got the answer at npmjs site. npmjs site for redis-connect package
After version 4, small code change is requried. "legacy-mode" needs to be enabled and explicite 'connect' call need to made in code.
The changed and working code is as below. Added the comments for the changes.
const RedisStore = connectRedis(session)
//Configure redis client
const redisClient = redis.createClient({
host: 'localhost',
port: 6379,
legacyMode:true //********New Addition - set legacy mode to true.*******
})
redisClient.on('error', function (err) {
console.log('Could not establish a connection with redis. ' err);
});
redisClient.on('connect', function (err) {
console.log('Connected to redis successfully');
});
redisClient.connect(); //******** New Addition - Explicite connect call *********
//Configure session middleware
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: 'secret$%^134',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // if true only transmit cookie over https
httpOnly: false, // if true prevent client side JS from reading the cookie
maxAge: 1000 * 60 * 10 // session max age in miliseconds
}
}));