How does app.use() work?

Question

How does app.use() work?

Answer
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.

1 Like

Ok, so my solution for calling timeMiddleware was correct except for this part:

app.use('/', timeMiddleware);

Obviously the error checker didn’t expect the path argument. Took me a while to realise that the path is in this case redundant, lol.

However I wonder if my solution should fail. Wouldn’t it work?

1 Like

@michal3926405177 I think specifying a path is not correct in this case, as this would mean that the middleware is only executed when the path matches. So to give an example, if a GET request with the path /snacks is received, your middleware won’t be executed as it only matches requests with a '/' path.

1 Like