DEV Community

Linh Truong Cong Hong
Linh Truong Cong Hong

Posted on

Question: What is middleware in web development?

It is not quite clear for me about the definition, functions and the neccessity of middleware in web development.

Can anyone have a clear explanation about what this is and why we need it in a web project?

Thank you!

Top comments (2)

Collapse
 
valeriavg profile image
Valeria

Imagine a conveyor in a Santa toy factory. One elf is dedicated to sorting broken toys out, the next one paints the toys, the third one packs them and so on. Each elf is a middleware.

On each incoming message middleware can either intercept it or modify it and pass it to the next middleware.

# Pseudo code

# Middleware
fn handle_json(req, res, next){
 if req.accepts("json") { 
   res.send({foo:"bar"})
   return 
 } 
 next()
}

handler= create_request_handler(
 handle_json, # middleware
 handle_html, # middleware
 handle_files, # middleware
 answer_with_404 # middleware
)
server = make_server(handler)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
andreidascalu profile image
Andrei Dascalu

A Middleware is a bit of code (can be a function or another application) that executes before the code meant to handle a given operation.

Imagine a classic setup where you have a some controllers each handling a given uri.

To make sure there authentication check for all of them, instead of beginning each controller with an if 'authenticated' do this else return unauthorized, you would use a Middleware which would return the unauthorized early else pass execution to your controller.

In frameworks this is usually done for you behind the scenes via configuration in some common cases