DEV Community

Cover image for What Is Middleware?
Hasan Elsherbiny
Hasan Elsherbiny

Posted on

What Is Middleware?

The Middleware as a definition can be considered like a broker which exist between two things to facilitate communication and data processing.

The Web Architecture is Mainly Based On Request Response Model, which mean the communication is happening in the shape of request and response, but what if i want to execute something between the request and response?

here comes the Middleware, Middleware is a piece of code that is being executed during/before or after the request execution.

it also can be registered to be fired for every request, so we don't need to handle every single request separately

Middleware can be used in both frontend and backend.

Middleware In Frontend

mostly it's called interceptors as it intercepts outgoing requests to append some useful headers such as auth headers and selected language.
it can also be registered to execute action in case of some types of responses like logging failed requests

Middleware In Backend

in most cases we need to authorize some requests and as frontend is sending auth headers with requests we need to capture these headers and check if they are valid or we need to deny the request
we don't need to handle this cases for each request (remember DRY Concept), so we can make a good use of Middleware.
in backend ,Middleware is also known as requests filters.

we can have as many as middlewares as we need in our application, but make sure they are necessary, they don't overlap with each other and they don't affect the app performance
in conclusion

Why Do we need to use Middleware ?

  • Request Processing
  • Response Processing
  • Cross-Cutting Concerns
  • Flexibility and Extensibility
  • Separation of Concerns

Most Common Uses of Middleware

  • Authentication and Authorization
  • Error Handling
  • Logging and Monitoring
  • Request Parsing and Validation
  • Compression and Caching
  • Routing and URL Rewriting

Top comments (0)