So after getting into express.js for about a month now, I find myself writing my own middleware methods now. If you do not know what middleware is then this post might be of help. A middleware is a module, or actually even just a method that does something with incoming traffic in an express.js application. There is moddleware for doing all kinds of things, like authentication, setting http headers, and parsing cookies just to mention a few things that can be done with middleware. In other words it is a term given to plugins, or extensions for express.js, as by itself I can only do so much. So this is where middleware comes in.
In this post I will be writing about making my own middleware methods, rather than using what is out there. However do look at what is out there for sure, however when making my own app there is going to be a need to write at least a few of my own, so I will be giving some examples here.
In this section I will be covering some basic examples of middleware.
So a simple middleware can be just be a single method that is given to app.use like this.
This middleware appends an object in the request object that can then be used later in the app, as I get to another section that responds to get requests I send that object as a response. Many middlewares do something like this, they append some kind of useful data to a response object that can later be used with other middlewares, and paths when it comes to rendering.
When doing some kind of aysnc task, such as reading a file, make sure that you are calling next in the right place.
in this example I am using the file system module to read the package.json file of the demo I am making for this post. The plain old fs module by itself uses callbacks, it is in that callback where I will be calling next. In other examples that involve promises I would want to call next in a method that is given to then, or catch.
An array of methods can be given to app.use. This is useful when I need to do something that involves many different steps, as I can break it down into many smaller parts.
Also I can pull each of these methods into a sepearte file in which I am exporting them, then bring them into this with require.
So I can have a app.js like this:
That uses another app in another file that is exported like this:
This post does not do everything that there is to write about with middleware justice, but if you are new to this sort of thing hopefully this post has help gave you a good starting point.