How does app.use() work?



How does app.use() work?

The .use() method in express is a middleware handler, app.use() as we saw here will always run the contained middleware callback function that it receives every time we get a request, and it does so like an event listener.

Let’s think of express as a receptionist at our company, we have given it a very important position. .use() is us giving express tools to do its job how we need it done. Now, if the phone is ringing (a request from the phone route) our receptionist will call every app.use() that it has and from there implement the necessary ones, for example, handling multiple languages, to answer the call and be ready to interpret the request received from the phone to provide the proper response. If we set a .use() with a path /email/ and a middleware of company templates, we make sure that our express receptionist knows that it will only use those company templates whenever there is a request in an email, and so it will not try to use them when someone rings the doorbell or walks in.

The way the method works when it is called is that it sets each middleware in an array of objects related to the stack of app (the express object) which visually would look like so:

   [ { route: '', handle: [Function] },
     { route: '', handle: [Function: static] },
     { route: '', handle: [Function: bodyParser] },
     { route: '', handle: [Function: cookieParser] },
     { route: '', handle: [Function: pgPromise] },
     { route: '', handle: [Function: cors] },
     { route: '', handle: [Function] },
     { route: '', handle: [Function] } ]

then, in the case of this example, whenever we receive a request to any directory (because if we don’t pass a path to .use() it will default to root and everything after) it will grab this array and run through each object and it’s stored middleware function to use to work with the request, once handled we will build our response, but the job of use is now over in the cycle.