Reputation: 139
In node using express.js, I have a redis-based session set up thusly:
// Redis session
const sessionStore = new RedisStore({
client: getRedisClient(),
prefix: 'bl:',
ttl: parseInt(config.sessionTTL, 10),
logErrors: (err) => {
log.error('Redis session error', {
err_message: err.message,
err_stack: err.stack
});
}
});
app.use(session({
secret: config.sessionSecret,
store: sessionStore,
resave: false,
saveUninitialized: false
}));
The ttl parameter is typically set to 30 minutes, at the end of which the session dies quite nicely.
I now need to advise the user when 5 minutes or less remains of their session but can't find a way of determining when I hit that landmark.
I assumed (rather naively) the amount of time left would be stored in req.session, but when I display that it typically only shows the following:
Session {
cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true },
cookieChoiceConfirmationBannerSeen: 'seen',
accessPage: '/decision/application-reference',
appRef: '12345678'
}
How can I find how much time is left on my session? Should I use maxAge or expiry rather than ttl?
========= EDIT ========= Additial info: the code for getRedisClient:
const redis = require('ioredis');
const config = require('../config/config');
let client;
const getRedisClient = () => {
if (!client) {
client = redis.createClient({
host: config.redisHost,
port: config.redisPort
});
}
return client;
};
module.exports = {
getRedisClient
};
Upvotes: 1
Views: 528
Reputation: 24565
You should be able to get the ttl of the entry itself by calling your redisClient with the corresponding key, i.e. your defined key-prefix (default sess
) and the session-id. Something like this should work:
const prefix = 'bl:';
const redisClient = getRedisClient();
// Redis session
const sessionStore = new RedisStore({
client: redisClient,
prefix: 'bl:',
ttl: parseInt(config.sessionTTL, 10),
logErrors: (err) => {
log.error('Redis session error', {
err_message: err.message,
err_stack: err.stack
});
}
});
app.get('/get-session-ttl', (req, res) => {
redisClient.ttl(`${prefix}${req.session.id}`,((err, reply) => {
console.log("the remaining ttl is "+reply);
res.send("...");
}));
})
Upvotes: 1