I understand that req.flash()
has been removed from express 3.x (source) and it's recommended to use req.session
directly (ie, req.session.messages
).
This is not a problem, however I'm having a hard time figuring out how to display this information in the layout after redirects. I've tried something like
app.locals.messages = function() { return req.session.messages };
but we obviously don't have access to the req
object.
How can I display the contents of req.session.messages
after a redirect?
Just do:
app.use(/* my session middleware */)
app.use(function(req, res, next) {
res.locals.messages = req.session.messages
next()
})
and you will always have messages
in your view. It really doesn't have to be anymore complicated than that.
If you want, you can add your own flash
function.
app.use(function(req, res, next) {
var session = req.session;
var messages = session.messages || (session.messages = []);
req.flash = function(type, message) {
messages.push([type, message])
}
next()
})
And in your view just do message = messages.pop()
.
You can also use connect-flash https://github.com/jaredhanson/connect-flash