Enhance Your Express.js Backend with Middleware for Efficient Request Processing
Tags: beginners, programming, node, express
Published: 2024-04-06 07:53:40

### What is Middlewares in Express.js?

In the realm of backend development with Express.js, managing repetitive tasks like user authentication and input validation across multiple endpoints can become cumbersome and lead to code redundancy. However, there's an elegant solution at hand: Middleware.

### Let's understand using an example Why do we need Middlewares?

Whenever a user makes a new request to the backend, we need to do the following prechecks before resolving the request.

1) Check if the user is valid or not (Authentication)
2) do the input validation

One simple solution I can think of is to write the logic of authentication and input validation for each endpoint. This solution is good but not the best because we are repeating our code and increasing the code readability.

### What can we do to overcome this challenge?

## THE BEST SOLUTION IS TO USE MIDDLEWARES

### Before jumping into the implementation part, first understand the flow of code execution.


![Basic flow of the middlewares](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1qe2zfwscdofdirf9jh.png)

### Let's understand how to create the middleware 


```
const express = require('express');
const app = express();
app.use(express.json())


app.get('/courses' , userAuthentication , (req, res) => {
  //write the logic of getting all courses
})

app.listen(3000, () =>{
  console.log('server is running on 3000 port')
})
```
In the above code, we can see an endpoint ‘/courses’, and the purpose of that endpoint is to get all the courses. 

Before it gets the course and sends the response, we need to check whether the user is logged in or not, and then if a user is logged in, we can move forward and get all the course and send back the response.

```
const express = require("express");
const app = express();
app.use(express.json());

const userAuthentication = (req, res, next) => {
  //Let's assume you will write the logic for checking if a user is logged in.
  let isLogged;
  //islogged is a boolean value, and it will keep checking if a user is logged in or not
  if (!isLogged) {
    res.json({
      msg: "User is not logged in",
    });
  } else {
    next();
  }
};
app.get("/courses", userAuthentication, (req, res) => {
  //write the logic of getting all courses
});

app.listen(3000, () => {
  console.log("server is running on 3000 port");
});

```
middleware is nothing but a JS function, and it has three parameters 

1) req object
2) res object
3) next() —> The purpose of this method is to move the controller to the next middleware.
### Execution Flow
1) The user hits the endpoint ‘/courses’

2) The controller will call the middleware userAuthentication

3) userAuthentication will check if the user is logged in. if logged in, it will call the next(), and there is no more middleware; the controller will reach the end and get the courses. if not logged in, the user will get a response saying, “User is not logged in.”

By leveraging middleware, you achieve:

- Improved code readability and maintainability.
- Centralized handling of common tasks like authentication and validation.
- Modular architecture, facilitating easier debugging and testing.

![Easy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jag372nqhqpaa8monlo.gif)