Saturday, February 25, 2012

Express.js Dynamic Helpers vs. Middleware

If you're build a site in express.js that relies on variables being set on every single page you may be tempted to use middleware and for a long time I've done something like this. It works fine.

// app.js file
var middleware = require('./util/middleware')

// middleware.js file
exports.setLocals(req, res, next) {
  res.local("currentPageName", applyFancyFormatting(req.url))
  res.local("luckyNumber", Math.floor(Math.random() * 100))

Express has something called dynamicHelpers that were built specifically with this in mind. It's a little bit simpler and in my opinion cleaner. It also doesn't make you next() after each one. You can put this anywhere you'd put an app.use statement. Check it out:

    currentPageName: function(req, res) {
        return applyFancyFormatting(req.url)
    luckyNumber: function() {
      return Math.floor(Math.random() * 100))

Or you can be like me and store them in different files like this:

// app.js
var dynamicHelpers = require('./util/dynamicHelpers')

// utils/dynamicHelpers.js file
exports.currentPageName = function(req, res) {
    return applyFancyFormatting(req.url);
exports.luckyNumber = function() {
   return Math.floor(Math.random() * 100);

See it's great isn't it? What do you think?


  1. Thank you for this post. Now that ExressJS no longer supports helpers, I was looking for a solution to make everyauth work in my jade views. Your "before" case gave me a good idea.

  2. Lol was searching for the 2 to 3 migration doc and this popped up. Funny they went back to middleware and canned the dynamic helpers.

  3. I have reviewed your blog and get knowledge about Business Intelligence.