DRYing code in express.js using app.use()

Image from Brain Technosys

In this article, we will investigate several ways to avoid replication/duplication of code and reduce complexity. Generally, in programming, this means putting the reused code into reusable containers like functions and objects. In express specifically, this will also mean composing our desired functionality into a series of Middleware functions.

Before we proceed first let us see what exactly DRYing code means?

What do You mean by DRY?

Don’t repeat yourself (DRY, or sometimes do not repeat yourself) is a principle of software development aimed at reducing repetition of software patterns, replacing it with abstractions, or using data normalization to avoid redundancy.

A code that performs the same task in multiple places is repetitive and the quality coder’s credo is “Don’t Repeat Yourself” (DRY). Duplication can lead to maintenance nightmares, poor factoring, and logical contradictions.

Illustration of DRY :

const addFive = number => {
const fiveAdded = number + 5;
console.log(`Your number plus 5 is ${fiveAdded}`);
}

const addTen = number => {
const tenAdded = number + 10;
console.log(`Your number plus 10 is ${tenAdded}`);
}

const addTwenty = number => {
const twentyAdded = number + 20;
console.log(`Your number plus 20 is ${twentyAdded}`);
}

We can achieve the same thing with less code.

const addNumber = (number, addend) => {   
const numAdded = number + addend;
console.log(`Your number plus ${addend} is ${numAdded}`);
}

As you can see, by adding an argument to the earlier functions we can simplify our application code which will ultimately save time.

DRY in express :

Suppose we are writing server code for a social media app that allows us to update and create new posts.

It is very important to verify a user is logged in before proceeding with request, therefore we will need to authenticate the user first.

Suppose we have 3 routes , we need to authenticate the user for each routes before performing any operation.

Example:

This is a very tedious approach and involves lots of duplication of code.

We can solve this issue by writing a middleware function that authenticates a user and pass this middleware as a callback to the HTTP method get(), post(), put() etc.

const authenticate = (req, res, next) => {
//authentication
...
...
...
if (authenticationSuccess){
next(); //Calls the next middleware in stack
} else {
res.status(404).send('Invalid User');
}
};
app.get("/posts/:id", authenticate, (req,res,next)={
//fetch posts
});app.post("/posts", authenticate, (req,res,next)=>{
//create new post
});app.put("/posts/:id", authenticate, (req,res,next)=>{
//update new post
});

We have tremendously reduce the duplication of code using authenticate() middleware.

By now you may have noticed that our efforts to not repeat ourselves have resulted in us putting the same function call over and over throughout our code. Isn’t that somewhat contradictory? You would be absolutely right to think so.

Thanks to express we can further DRY our code using the express app.use() middleware method.

const authenticate = (req, res, next) => {
//authentication
...
...
...
if (authenticationSuccess){
next(); //Calls the next middleware in stack
} else {
res.status(400).send('Invalid User');
}
};
app.use(authenticate);
app.get("/posts/:id",(req,res,next)={
//fetch posts
});app.post("/posts",(req,res,next)=>{
//create new post
});app.put("/posts/:id",(req,res,next)=>{
//update new post
});

The app.use() takes a callback function that it will call for every received request. In this example, every time the server receives a request, it will find the first registered middleware function and call it. In this case, the server will find the callback function specified above, call it, and verify the user.

Summary

By now you can figure out writing non-repetitive good code by following these simple techniques.

  • Duplication can lead to maintenance nightmares, poor factoring, and logical contradictions.
  • Use app.use() for avoiding duplication of code.
  • Useful links :

Thanks for reading! If you enjoyed this article, please click the 👏 button and share to help others find it! Feel free to leave a comment 💬 below.
Have feedback? Let’s connect
on Twitter.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store