Middleware is literally everywhere in express. You can make an argument that express apps are nothing but bunch of middleware stuff together.

The flow is:

Request ⇒ Middleware ⇒ Response

In middleware we will do something with the request, etc.

Screenshot 2022-08-28 at 6.39.10 PM.png

This is a simple middleware which just logs info about the request.

Note: Express passes the req,res and next in the logger for you. We’ll talk about next later.

Screenshot 2022-08-28 at 6.40.18 PM.png

Screenshot 2022-08-28 at 6.39.41 PM.png

You can see, although we get correctly logged the browser just keeps on loading.

This is because we logged but did not pass it on to next middleware. So, the thing is when you work with middleware you must pass it on to a next middleware, unless you are terminating the whole cycle by sending back the response.

So, you can to add res.send at the end:

Screenshot 2022-08-28 at 6.42.48 PM.png

Screenshot 2022-08-28 at 6.43.15 PM.png

Screenshot 2022-08-28 at 6.43.07 PM.png

Now, you can see it is working. Here, by doing res.send() we terminated the whole cycle of passing from one middleware to another, and sent a response.

Now, to pass to next middleware:

Screenshot 2022-08-28 at 6.46.18 PM.png

Here, you can see we used next() instead of sending a response. Now, we can use this logger middleware in about route as well. This will save us lot of lines of code.