DEV Community

Cover image for What Is Middleware?
Hasan Elsherbiny
Hasan Elsherbiny

Posted on

20 5 4 4 5

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️