I am using in my express app the message alert middleware connect-flash. I can find this middleware on github https://github.com/jaredhanson/connect-flash.
When i look at connect-flash source code, i really don't know, where the this.session object come from. Consider the connect-flash source code:
module.exports = function flash(options) {
options = options || {};
var safe = (options.unsafe === undefined) ? true : !options.unsafe;
return function(req, res, next) {
if (req.flash && safe) { return next(); }
req.flash = _flash;
next();
}
}
function _flash(type, msg) {
if (this.session === undefined) throw Error('req.flash() requires sessions');
var msgs = this.session.flash = this.session.flash || {};
if (type && msg) {
// util.format is available in Node.js 0.6+
if (arguments.length > 2 && format) {
var args = Array.prototype.slice.call(arguments, 1);
msg = format.apply(undefined, args);
} else if (isArray(msg)) {
msg.forEach(function(val){
(msgs[type] = msgs[type] || []).push(val);
});
return msgs[type].length;
}
return (msgs[type] = msgs[type] || []).push(msg);
} else if (type) {
var arr = msgs[type];
delete msgs[type];
return arr || [];
} else {
this.session.flash = {};
return msgs;
}
}
To implement in express, i have to include within the app.configure block. Consider the code
app.configure(function () {
//Other middleware
app.use(function (req, res, next) {
console.log(this.session);
next();
});
app.use(flash());
Look at my custom middleware, when i display this.session object, i got "undefined". Why is this.session in connect-flash working, i get overthere the session object, but not in my middleware. The callback pattern for create a middleware are exactly the same
(function (req, res, next) {
//Code
next();
}
The session object is added by the session middleware. If req.session
is undefined you either don't have the session middleware defined or you defined it after the middleware where you are expecting it.
Defined
Undefined
So my guess is that you defined the flash middleware after express.session
but your custom middleware is defined before express.session
.
Since express is just an array of functions (middleware) that does stuff to the request and returns a response means that the order in which you define those functions matters.