DEV Community

Discussion on: Question: What is middleware in web development?

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