Doing Away with Express-Messages

Although I was recently appointed as a maintainer of express-messages by the expressjs organisation I no longer use it any of my projects. There’s a lot I don’t particularly agree with – HTML as strings, lack of support for templating engines and particularly the way it locks you into a structure – but I can’t deny it’s been very useful to me in the past and I hope I can keep it that way for others in the future.

So I’m going to show you what I do instead. Lets get rid of that app.use(require('express-messages')()) and replace it with:

app.use(function (req, res, next) {
  var flash = req.flash()
  res.locals.messages = Object.keys(flash).reduce(function (messages, type) {
    flash[type].forEach(function (message) {
      messages.push({type: type, message: message})
    })
    return messages
  }, [])
  next()
})

What we’re doing here is taking the object of arrays generated by connect-flash and turning it into an array of objects so I don’t have to do any fiddly logic to include it in my templates. If I’m using Jade (my personal favourite) I can do this:

ul.messages
  each message in messages
    li(class="#{message.type}")= message.message

and if I’m using EJS I do this:

<ul class="messages">
  <% messages.forEach(function (message) { %>
    <li class="<%= message.type %>"><%= message.message %></li>
  <% }) %>
</ul>

Now instead of asking express-messages to concatanate some strings into HTML for us to include as a function in our template we get a nice messages array on the locals object that we can include wherever and however we want.