jaredhanson/connect-flash

Is it compatible with Express 4.X?

alvarotrigo opened this issue · 5 comments

Is it compatible with Express 4.X?

using it with 4.x -> view express-session

@Naxmeify that's about sessions, not really about a flash message.
You would have to destroy the session manually after the page is render. Not the same.

It seems connect-flash is compatible with Express 4. I'm using it. But it's not perfect. Couldn't manage the pass the type of message (error, status, info...)

https://github.com/expressjs/flash is the Express 4 version.

@alvarotrigo Yeah I thought everything was good because I reverted back to connect-flash and everything works fine (expressjs/flash not working). Then I read this and realized I was not using the message type.

Here is something I just did which works.

set messages variable as object containing separate error/info messages

res.render('signup', {
      title: 'Sign-up Form',
      messages: {
        error: req.flash('error'),
        info: req.flash('info')
      }

Problem here is you end up with an empty array if there are no info messages or visa versa so in your template you have to check for array.length

flash them where ever like normal

if (err) {
              var message = getErrorMessage(err);
              req.flash('error', message);
              req.flash('info', 'foobar');
              return req.res.redirect('/signup');
            }

In my ejs template

<% if (typeof messages.error !== 'undefined' && messages.error.length > 0) { %>
    <p class="error"><%= messages.error %></p>
<% } %>
<% if (typeof messages.info !== 'undefined' && messages.info.length > 0) { %>
    <p class="info"><%= messages.info %></p>
<% } %>

Could place this in it's own template to be included or create some type of helper function globally available to all views like

<% if(messages) renderMessages(messages); %>

Just a thought.

Update: Just realized no need to explicitly set error and info in the messages variable since simply calling messages: req.flash() already does this. https://github.com/jaredhanson/connect-flash/blob/master/lib/flash.js#L41