Photo by Pankaj Patel on Unsplash

I’ll explain how I refactor my code to be self-documenting, clean and enforcing DRY (Don’t repeat yourself) when developing routes in express.js using middleware. I don’t want to bore you with unnecessary information, so I’ll jump right to the point.

Let’s take a look at this example

This example is made up and not used in a real application, just try to get the concept behind this code, there may be small errors in the code but again it’s about the idea, not the code itself.

It’s clear that this code is messy (and not complete, this is just example and not used in any application, I’ve also cut some stuff to not make it as long) and what if you want to create another route that uses the same code from this route (check for input validation, get a connection to the database, etc.. )?

You could add a new function and it will be perfectly fine, but I think a better solution is to make a couple of middleware (especially if they are going to be used in multiple endpoints).

The code after refactoring

I will usually put the middleware on different files but for this example, it’s on the same one.

The good thing about this is that when you look at the endpoint code you can clearly see what’s happening and in what order (remember! order matter). The name of the middleware self-document the requirement for the endpoint and tell you what the route does. I usually put the middleware in a sperate file, keep the router file cleaner and less crowded.

We can now reuse the middleware

The good part about middleware is that we can re-use them easily. Let’s say I want to create another endpoint that will list all the group members of the user current group. All I have to do is this:

Why should you use middleware instead of functions

Functions are fine but they are limited. using middleware we can get a hold of the request and response object and send error message or manipulate the request object as needed, overall it allows you to have more control while still avoiding code repetition.

Thank you for reading, feedback is always welcome.