jaredhanson / connect-flash

Flash message middleware for Connect and Express.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is it compatible with Express 4.X?

alvarotrigo opened this issue · 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...)

commented

@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