What is middleware?
Middleware is an entity that hooks into a server's request/response processing. The middleware can be defined in many components. Each component has a specific function to perform. Whenever we define the handlers for our URL patterns (as in the last chapter), the request hits the handler and executes the business logic. So virtually all middleware should perform these functions in order:
- Process the request before hitting the handler (function)
- Process the handler function
- Process the response before giving it to the client
We can see the previous points in the form of a visual illustration:
If we observe the diagram carefully, the journey of the request starts with the client. In an application with no middleware, a request reaches the API server and will get handled by some function handler. The response is immediately sent back from the server and the client receives it. But in applications with middleware, it passes through a set of stages, like logging, authentication...