What is Middleware in Express.
How it's Works .

What middleware is in Express .
So when you see the word middleware, you can think of it like a middleman. There are two parties, and between them there is a middleman.
Now assume data comes from one party, first it goes to the middleman. You can also call it a broker. First, it validates the data, and then if the data is valid, it forwards it to the second party.
Similarly, in programming, middleware works in the same way. We know that a client sends a request, and that request goes to the server.
So the role of middleware here is that it first intercepts the request before it reaches the server. It checks or validates the data, and if everything is fine, then it passes the request to the server for further processing. If not, it rejects the request at that point itself.
So this is the basic overview of middleware. In the next section, we will see how middleware works internally and how it is written in Node.js.
Where middleware sits in request lifecycle .
Whenever a client sends a request, it does not go directly to the server logic or controller. The request first enters the application, and before reaching the final handler, it passes through middleware.
So middleware sits in between the incoming request and the final response.
Below is a code so first see him then we discuss how it's work.
router.route("/profile").post(auth, userDetail);
- Now you can see in this code we have first route where user sent request, it is a post request, in post we have two parameter, first one a middleware and second one is a controller who interact with server, so before going to request to server, first go to middleware they check first and then after that go to user. This is how middleware work.
Types of middleware :-
So middleware can have different types, because in middleware you basically write some logic. Once that logic is written, whenever data comes from the client, it is first handled by the middleware.
What happens is, it validates or checks the data before the request goes to the server.
This validation can be done in different ways. It can be applied to the whole application, or to a specific route, or even to specific data in the request. Some checks can also be done using built-in middleware provided by the language or framework.
So now, based on how and where this logic is applied, middleware can be of different types. we will look at how many types of middleware exist and how they work.
Application-level middleware :-
So application-level middleware means that it runs on the entire application, not just on a specific request.
That means any request that comes into the app has to pass through that middleware and follow whatever logic or requirements are defined in it.
These middleware can be built-in, or they can be custom middleware created by you.
So in simple terms, application-level middleware applies globally to all routes and all incoming requests in application.
app.use(express.json()); // built in middleware. app.use((req, res, next) => { console.log(`Request body data`, req.body); return res.status(200).json(req.body); next(); })
Router-level middleware :-
So in router-level middleware, the middleware is applied on a router instead of the whole application in Node.js.
That means it works only for a specific group of routes, not for every request in the app.
For example, if you have a user route file, you can apply middleware in two ways.
Either you apply one middleware on the entire router, so every request inside that route file goes through that middleware.
Or, if that file has multiple routes assume have 4 - 5, you can apply different middleware on each route separately based on your needs.
So in simple terms, router-level middleware gives you control to apply middleware on a group of routes or on specific routes inside that router.
Built-in middleware :-
- Built in middleware means library or framework have it's own middleware for specification, used it globally , below is some example of built in midlleware , but there are lot's of built in middleware are accoring to use case .
app.use(express.json()); app.use(express.static('path');
Execution order of middleware .
When a request comes in, it starts from the first middleware, then moves to the next one, and continues like a chain. Each middleware decides whether to pass control using next() or stop the request.
Role of next() function .
So now let's understand the role of next() function in middleware.
When a user sends a request, it first goes to the middleware before reaching the server logic.
Now inside middleware, we usually have two scenarios, either the data in the request is valid or it is invalid.
If the data is invalid, we return a response from there itself with an error.
But if the data is valid, then we need to send that request forward to the server so it can process it and send a response back to the client.
So how do we forward that request?
For that, we use the next() function.
The role of next() is to pass control from the current middleware to the next middleware or to the final route handler server controller or it's service.
So when you call next() function, it means:- This middleware is done, now move to the next step.
If you do not use next() function, then the request will get stuck inside the middleware and will never reach the server
That's why next() is very important.
Real world examples :-
Logging :-
- In logging, what happens is that when a user wants to log in, they send their details. Now we cannot fully trust that the user will send correct details, so to validate this, we first take the user’s data from the request and then check those details using middleware to see if they match our conditions or not. That's how it is verified.
Authentication :-
- In authentication, what happens is that at the time of login, the user is given a token, and that token contains the user’s details. That token gets stored with the user. Now, the next time the user comes, they will have that token, so we first need to validate that token and check whether the user inside it exists in our database or not. If the user exists, then we allow the request to proceed. All of this is also handled using middleware.
Request validation :-
- In request validation, the same concept applies — we check whether the user making the request actually exists in our database or not. If not, we reject the request. For example, we can validate the user's ID to check whether it exists or not.




