Search code examples
javascriptnode.jsexpressroutesexpress-4

Bundling Middleware


Background

I'm writing a web application using Node/Express 4 on the server.

Some of my routes need to be open to the public, but other routes need to be secured using token authentication. The process of performing the token authentication essentially breaks down to the following 4 pieces of middleware:

router.post('/api/my-secure-endpoint',
  check_token_integrity,
  check_token_expiry,
  check_route_permissions(['perm1', 'perm2',...]),
  refresh_token_if_necessary,
  ...
);

check_route_permissions is actually a function that returns a customized middleware function for the provided route permissions, but otherwise isn't special in any way.

Question/ Problem

I feel that it's rather WET to have to write these out all of the time. Is there a way to create a bundle, e.g. authenticate that is essentially just a place holder for these middlewares?

Whats the common pattern for this?

Possible Solution

I could create a function that returns an array whose elements are the middleware functions and then flatten it myself, e.g.

function auth(perms) {    
  return [
    check_token_integrity,
    check_token_expiry,
    check_route_permissions(perms),
    refresh_token_if_necessary,
  ];
}

router.post.apply(this,
  _.concat('/api/my-secure-endpoint', auth(['perm1', 'perm2']), [my, other, middlewares]));
);

However, I'm wondering if there is a cleaner or more standardized way of doing this.


Solution

  • Express supports arrays of middleware, so this'll work:

    router.post('/api/my-secure-endpoint',
      auth(['perm1', 'perm2']),
      [your, other, middlewares],
      ...
    )
    

    More info here.