Abusing Express Middleware

Harry Martland
DailyJS
Published in
3 min readJan 10, 2020

--

It is easy for any application to become hard to maintain. Breaking it down into small sections allows for each unit to be tested, understood and have a single responsibility.

Express’s middleware feature is a great way of splitting up your service. When I first learned about express I found little use for middleware but now I would be tempted to say I abuse it. Below are some middleware patterns you may want to consider.

Loading Data

By extracting the data load out of your routes you keep them simple to read, understand and test. Middleware can add content to res.locals which makes it available in templates and other middleware. You can reuse data middleware for multiple routes reducing code duplication and multiple middlewares can be registered when defining routes e.g;

Routers can also be used to run data middleware on all routes registered in it keeping the route definitions simple e.g.

--

--

Harry Martland
Harry Martland

Written by Harry Martland

Principal Software Engineer at Booking.com — Transport, writing mainly about observability, reliability and building applications ‘well’