0
votes

I am attempting to fully understand what middleware is and I've come to bit of a hardspot.

I'm reading through the expressJs docs and its definition of a middleware function which is - "Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next."

I know the next variable doesn't have to be titled "next" to have the func.

I also know there is a difference between middleware(like monogJs) and a middleware function/method(app.use()). In angular the http module also follows this pattern, as do other things within angular and other prevalent frameworks. Are these also considered middleware? Could someone provide clarity for me?

1
No, the middleware is between the browser and the http server - Sebas

1 Answers

2
votes

A middleware is a piece of code that gets executed before and or after every request. This helps you create shared functionality like logging and authorization without having to implement the code for each of your endpoints.

The order of the middlewares are commonly called the middleware chain.

app.use(middleware)

This is the way we attach middleware to every request. When it comes to the database connection we tend to leave it out of the request endpoints becuase it is something that is application global.

Now, the reason we have next is to tell the chain when a function is completed. This is a callback pattern. We also want to be able to pick up errors (Exceptions) in the chain so we can add shared functionality to our application for it. JavaScript is not type defined so we the only way to register the difference between two functions are the amount of registered arguments. That's why error handling has 4 arguments.

Here is an example of an endpoint with logging and error handling

app.use(function(req, res, next) {
  console.log('request made to server');
  next();
});

app.use(function(error, req, res, next) {
  console.log('an error occurred in the code');
  next();
});

app.get('/', function(req, res) {
  /* Your logic here */
});

If you have specific middleware you wish to use for only a few endpoints, you can register them directly

app.get('/', middleware, function(res, res) {
  /* Your logic here */
});

I hope this helps to understand middleware. Middleware is a part of the processing stack, not a protocol invocation.