13

-- EDIT --

I wrote some middlware to do this: https://npmjs.org/package/flashify


So since the release of Express 3.0, the changes have removed req.flash()

https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x (source)

So here is my question now. They have advised to use req.session.messages in a local to display a flash.

So to make a session accessible to the view, we have to do the following:

nb: In coffee-script

app.locals.use (req,res) ->
    res.locals.session = req.session

How would we access the session data from the view then clear it? We can't clear the contents of session after the view has rendered, but we can't clear it because it wont reach the view so im a bit lost as to how one would get around this problem?

1
  • Just as a question of technique, you would generally get the message out of the cookies/session whatever, delete that permanent one, than just store it as a request local sort of variable. You would do this early on when it can be done, then by the time the view is rendered, it just sees the local version. Dec 31, 2012 at 19:16

5 Answers 5

30

You can use the connect-flash middleware to add the req.flash() functionality back into express 3.0.

0
7

I believe they simply moved req.flash to req.session.messages

5

From Tim's link above:

This middleware was extracted from Express 2.x, after Express 3.x removed direct support for the flash. connect-flash brings this functionality back to Express 3.x, as well as any other middleware-compatible framework or application. +1 for radical reusability.

Express 2.x migrate to 3.x page says the following:

  • req.flash() (just use sessions: req.session.messages = ['foo'] or similar)
5

Besides connect-flash and express-flash, there's also just flash, which is made by the expressjs team (which I consider as a bonus). Super simple to use:

install:

npm i flash

app.js:

app.use(session()); // session middleware
app.use(require('flash')());

app.use(function (req, res) {
  // flash a message
  req.flash('info', 'hello!');
  next();
})

view.jade:

while message = flash.shift() // consume messages as jade reads them
  a.alert(class='alert-' + message.type)
    p= message.message

Note how the code above shifts them; if you just read the array, the flash messages keep hanging there in the session (which is great for redirects).

1

Install connect-flash middleware, require it, then

app.use(flash()) and note it should be appear before app.use(express.session...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.