DEV Community

loading...

Question: What is middleware in web development?

linhtch90 profile image Linh Truong Cong Hong ・1 min read

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!

Discussion (3)

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
lifelongthinker profile image
Sebastian • Edited

There are various connotations for the term "Middleware". I take it you are referring to the middleware found in modern web frameworks.

In that context, middleware is any code that runs in between the base OS layer (accepting incoming requests) and your application logic.

Imagine it as the layer in the middle of the base layer (usually OS-related stuff like accepting incoming requests) and your application layer.

As such, middleware frequently handles cross-cutting concerns, e.g. authentication, logging, monitoring, data conversion, ...

To really get a grasp of the topic, have a look at Wikipedia to see where the term comes from and how it's used in different contexts.

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

Forem Open with the Forem app