Exclude WebApp.rawConnectHandlers.use from a list of routes

Hey all! I am currently using the WebApp.rawConnectHandlers.use() method on my main server file to load data into the head of all routes using req.dynamicHead.

I am sure this is possible, but I am not sure how to execute it, how would I exclude the sting I am injecting into the head from a list of routes? (I am using flow-router).

I found this part of the docs where it shows how to use it for a single route:

https://docs.meteor.com/packages/webapp.html

I am basically just trying to do the opposite, but with multiple routes.

Perhaps use route path patterns?

https://expressjs.com/en/guide/routing.html

1 Like

Or do something like

WebApp.connectHandlers.use((req, res, next) => {
  if (['my', 'blacklisted', 'urls'].includes(req.originalUrl)) {
    // do nothing
  } else {
    // do your thing
  }
})
2 Likes

@tomsp lol SO OBVIOUS! I must have been having a senior developer moment. :stuck_out_tongue:

Thanks!!

1 Like

Just a small performance optimization to @tomsp’s answer, particularly if your array of excluded routes is large:

  1. Define the array outside the handler, so that it doesn’t have to be re-created on every page load.
  2. It seems that Set.has() is 5x faster than Array.includes().

Also, don’t forget to call next() if you are only intercepting the request and not dealing with it.

const excludedRoutes = new Set(['my', 'blacklisted', 'urls']);

WebApp.connectHandlers.use((req, res, next) => {
  if (excludedRoutes.has(req.originalUrl)) {
    // do nothing
  } else {
    // do your thing
  }
  next();
})
1 Like

@wildhart Great call. :slight_smile: This was my plan.

@wildhart @tomsp

Just a quick question…if I wanted to target all url’s in a directory, would I do something like:

/sub-directory/*

Looks like I am going to need something like this.

Also, is there a way to have this fire upon entering each route? As it stands it seems that the page would need to reload in order for this to fire…

That’s a wildcard matching pattern and it should work. See my original answer and also this SO question: https://stackoverflow.com/questions/6161567/express-js-wildcard-routing-to-cover-everything-under-and-including-a-path

EDIT: I realised that you are trying to do all this using only the pure Connect handler in Meteor. In that case you cannot use a pattern. For advanced context matching there is a powerful middlleware which you can drop straight into Meteor: https://github.com/chimurai/http-proxy-middleware

Create your Express based proxy like int their readme, then plug it into Meteor:

WebApp.connectHandlers.use('/sub-directory', proxy);