DEV Community

Margaret W.N
Margaret W.N

Posted on

Middleware

Middleware is like a middle man in a business transaction, the only difference is middleware saves us time and money unlike middle men. It's a term coined to refer code that executes in between sending a request to a server and receiving a response. It is one way to adhere to the DRY(Don't Repeat Yourself) software development principle.

In express we use app.use ( ) to leverage on middleware function calls. We pass an arrow function to .use ( ) that takes three parameters req, res and next where next is a callback function. The callback function fires the next operation and passes the data from the arrow function.

app.use((req, res, next) => {});
Enter fullscreen mode Exit fullscreen mode

So now any redundant code can be bundled up in the arrow function body, and executed in between processing the request.

Top comments (3)

Collapse
 
andrematias profile image
André Matias

Nice!!!
Is that like a Decorator pattern? Or some like that?
Wikipedia

Decorator Pattern UML

Collapse
 
mtee profile image
Margaret W.N

Yes they exhibit similar functionalities. There are very minor differences though. Here is a discussion on the differences.

Collapse
 
katherine95 profile image
Catherine Chepkirui

Wow! this is great🔥