Search code examples
node.jsexpressnode.js-connect

Common Pre-Handler for ConnectJS/ExpressJS url handlers?


In my ExpressJS app, several of my urls handlers have the following logic:

  1. See if the user has permission to access a resource
  2. If so, continue
  3. Else, redirect to the main handler.

Is there a way to insert a pre-handler for certain url handlers, via ConnectJS or ExpressJS?

I know I can do it globally, for all handlers, (which I do to insert missing headers as a result from IE's broken XDR).

But, can I do this for a subset of handlers?


Solution

  • I do something like this:

    lib/auth.js

    exports.checkPerm = function(req, res, next){
      //do some permission checks
      if ( authorized ) {
         next();
      } else {
         res.render('/401');
         return;
      }
    };
    

    app.js

    var auth = require('./lib/auth');
    ...
    app.get('/item/:itemid', auth.checkPerm, routes.item.get);
    

    You can stack middleware before your final route handler like the above line has. It has to have same function signature and call next();