Using router level middleware in Express

Adrian Oprea
2 min readDec 20, 2016

--

Recently, I decided to move some app-level middleware to the router level, on a project I’m working on. I opted to do this because I needed to add a /healthcheck endpoint that Amazon’s load balancer pings whenever a Docker service launches in ECS and I didn’t want any middleware to run for this as it only returns a 204 No Content status code.

Looking through the Express documentation, I found a lot of valuable information, in terms of how to bind middleware only to specific mount points (routes/endpoints), outlined in the example below.

The solution above is fine if your endpoints look like this: /orders/list. Unfortunately, many still work on applications with endpoints like this: /listOrders, /getTotal. This means that the elegant version above turns into the version below.

Think about adding 2 new endpoints? Happy copy-pasting 📋!

It is very common to use regular expressions in app routes, on larger applications so without spending more time on the docs, I did the same with mount points, and it worked flawlessly! Below is the code that matches any of the application’s order-related endpoints, and binds the middleware accordingly.

Adding a new endpoint? Just paste it in! In my opinion this is way more maintainable than the previous solution.

Make a request to /listOrders or /getTotal and the fantastic middleware will run! Conversely, if the load balancer pings the /healthcheck route, nothing but the route handler that sends the 204 gets executed.

Now, I have a small dose of OCD that I hide behind my passion for maintainability and readability. If you think the solution above still needs a bit of tweaking, you can turn it into something even more maintainable 🎉.

Now, you only need to add an extra item to the ENDPOINT_NAMES array and you’re good to go. In my opinion this makes things more maintainable, although some people might argue that it sacrifices readability.

I didn’t find any documentation related to regular expressions on the page about using middleware, in the express docs. I plan on getting in touch with the people behind it and if it is relevant, add this information to the docs.

--

--

Adrian Oprea
Adrian Oprea

Written by Adrian Oprea

Founder & CEO of WeRemote.EU. Remote work enthusiast. Bookworm.

No responses yet