Ionică Bizău Ionică Bizău - 1 year ago 102
Node.js Question

Make the specific routes in Express have higher priority than the dynamic ones

I have two routes added in this order:


The way how my app is structured is that the routes may be added dynamically. So, I do want to catch any site page (e.g.
, matched by
), but I do want that the specific route
to have higher priority than the other one.

I know that the middleware get executed in sequential order, so, ideally I have to change the order of the calls, but since this is happening dynamically, is there a better way to do it?

How can I tell Express that the routes without dynamic stuff in them (pretty much containing
) should have priority over the ones that are dynamic?

Answer Source

I don't think it's possible with "plain" Express, but this may work:

let Router   = express.Router;
let MyRouter = function() {
  let instance    = Router.apply(this, arguments);
  let handle      = instance.handle.bind(instance);
  instance.handle = function(req, res, out) {
    this.stack.sort((layer1, layer2) => {
      let path1 = layer1.route.path.replace(/:[A-Za-z0-9_]+/g, ':');
      let path2 = layer2.route.path.replace(/:[A-Za-z0-9_]+/g, ':');

      return path1.length < path2.length;
    return handle(req, res, out);
  return instance;
express.Router = MyRouter;

It basically monkeypatches the handle method of express.Router to sort the layer stack (which contains the routes) prior to handling the request. It sorts routes based on the length of the path (longer paths take priority), and hardcodes parameters in paths to have a length of 1 (so /:foo has a length of 2, and / has a length of 1; if you have paths like /x, you may have to fix this).

Very much untested, but at least it may provide an idea on how to tackle this.

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