I have set up my express/connect app to use sessions with redis as the store:
app.use(express.session({
secret: "secret key here",
store: app.redisStore,
cookie: { maxAge: 600000 }
}));
I have created my own flash message system by doing the following:
module.exports = function (app) {
'use strict';
//set-up session messages
app.use(function (req, res, next) {
/* set up flash*/
if (req.session.flash === "undefined") {
req.session.flash = [];
}
res.locals.messages = function () {
var messages = req.session.flash;
//clear out messages
req.session.flash = [];
return messages;
};
...
Then essentially I just push flash message objects into the flash array whenever I need them. Every time the message function is used they get cleared out. This seems to work for the most part; however, while logging out I use the regenerate function and flash becomes undefined:
function logout(req, res) {
var currentUser = req.session.currentUser;
req.session.regenerate(function (err) {
req.session.flash.push({"type": "info", "message": "You have been logged out."});
console.log(currentUser + " Logged Out");
res.redirect("/login");
return;
});
}
Which seems to make sense. Regenerate obliterates the session, and since it happens after the initial request flash becomes undefined. To avoid any future problems like this I am wondering if there is there some sort of initialize function for sessions that I can override or hook into? I’d use this to set some default session values every time a session is started or regenerated.
Side-question: Is flash actually getting saved in redis?
No, the way you are doing this is correct. If you want to attach multiple actions to
regeneratemethod, then you can also try something like this:Then you can simply do:
This is a monkey patch, though ( at least the
.regenerateoverriding ), so I advice writing your own session store, which is not difficult at all, since session is nothing else then an entry in Redis/any other storage.Yes, everything attached to
sessiongoes to session store ( Redis in your case ).