In express.js the concept of middleware is something that should be grasped in order to make significant headway with express applications. If you have fiddled around with express a little so far, chances are you have used some middleware so far without even realizing it. There is some express built in middleware, one example if this would be the express.js body parser, but for the most part express itself is fairly minimal. So as such creating a fairly capable express.js application will involve installing additional middleware, as well as writing original middleware functions. So then in this post I will be covering express middleware basics.
So a middleware method can be just a function that receives arguments for an incoming request, a response, and the next middleware to call after what has been done in the middleware method is completed. This method is then often used with am express app object method like app.use as a way to preform some kind of task involving an incoming http request of one type of another.
So for a very basic example here is a quick express app that just appends an rnd property to the request object of an incoming http request that is then used to render an incoming get request to the root name space.
All middleware does something like this, that is creating a property that is to then be used elsewhere, set a response header, get some information from a database or so forth. Once the task is complated the next method is called to continue the flow forward to the next middleware method or path.
More than one middleware method can be passed to the app.use method in the form of two or more arguments. It is always generally a good idea to break things down, and make things more fine grain. In other words breaking down a complex task into many smaller tasks that are to be preformed in a certain sequence rather than doing everything in a single method.
They can also be group together as an array of methods as well.
Breaking things down into separate functions is one thing, but it is also a good idea to keep things in separate files as well.
If you found this post helpful, and would like to read into some more advanced topics when it comes writing middleware be sure to check out my main post on express middleware. For more on express in general you might want to check out my main post on expressjs.