By now, we’ve already had some exposure to middleware: we’ve used existing middleware (
connect-session, to name a few), and we’ve even written some of our own (when we check for the presence of
&test=1 in the querystring, and our 404 handler). But what is middleware, exactly?
Conceptually, middleware is a way to encapsulate functionality: specifically, functionality that operates on an HTTP request to your application. Practically, a middleware is simply a function that takes three arguments: a request object, a response object, and a “next” function, which will be explained shortly. (There is also a form that takes four arguments, for error handling, which will be covered at the end of this chapter.)
Middleware is executed in what’s known as a pipeline. You can imagine a physical pipe, carrying water. The water gets pumped in at one end, and then there are gauges and valves before the water gets where it’s going. The important part about this analogy is that order matters: if you put a pressure gauge before a valve, it has a different effect than if you put the pressure gauge after the valve. Similarly, if you have a valve that injects something into the water, everything “downstream” from that valve will contain the added ingredient. In an Express app, you insert middleware into the pipeline by calling
Prior to Express 4.0, the pipeline was complicated by your having to link the router in explicitly. Depending ...