Express js – Creating your own middleware

One of the greatest things about Express is that it is easily extended, which is achieved by using middleware. Middleware are functions that handle requests, which are invoked by the Express.js routing layer and we can have N number of middleware on single request. In fact, our routes are just the final middleware function. We return a response, which means that at this point, the request is done and no more middleware functions are executed.

How to Write Middleware for Express.js Apps

Creating our own middleware

To create a middleware all you have to create a function and it should accept request, response, next parameter as arguments. so you will have full access to the request and response objects and you tell express to move on to next middleware.

Middleware skeleton

Never forgot calling next() method in the middleware right after your middleware logic finishes, it indicate that our middleware was finished and it takes to the next middleware or route . Express.js has no way of knowing when your operation is complete before it can continue to the next middleware or route so calling next() method is very essential.

To add a middleware layer to Express, we use app.use(), which allows us to inject a middleware function. Adding middleware is like method chaining one after other, so the order is matter.It means middlewares are always invoked in the order they added. So we can also override fields/data of other middleware.

Let’s take the most basic Express.js app:

The above Express.js app will respond with Hello World! to a request for / and “say hello” for requests to /hello.

Now what if you want to log every time you got a request to app. you could go to each method and add your logging logic, but what if you have 20+ methods, what if you want to remove logging, maintenance is very tough and its like nightmare. This is were middleware come it to play, here you can use middleware! let me show you.

That is it.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.