LukeP LukeP - 1 year ago 108
Javascript Question

Bundling Middleware


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:'/api/my-secure-endpoint',
check_route_permissions(['perm1', 'perm2',...]),

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.
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 [
_.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.

Answer Source

Express supports arrays of middleware, so this'll work:'/api/my-secure-endpoint',
  auth(['perm1', 'perm2']),
  [your, other, middlewares],

More info here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download