What is middleware?How it works in nodeJS?A Simple implementation

Christopher Zach
techimania
Published in
3 min readOct 5, 2019

Middleware function are the function that has control over request(req object) , response(res object) and next function that is going to be executed after the current function being executing in the applications request response cycle.

Whenever a user sends a request to server it uses request object and when the web application server sends a response to the browser , response object is being used.The next function is the function in the middleware that is invoked after the current function is executed. It makes changes to the request and response object.It finishes the complete request-response cycle.

Now comes to Implementation.

Middleware functions usually have 3 standard params req, res, and next. The first two are objects, the last is a function that will call the next middleware function, if there is one.

First we will check what happens if we not use next() in middleware

Here see we are not using next function().

Now we are starting our local server on port number 8080. as show in figure.

Here

We can see that when the user request on browser on local server the request-response cycle is not getting completed because we have not used next function in the middleware function myfun().The control is not proceeding from the middleware function (myfun() in our case). Hence the server is not able to response back to the browser.

Now comes to the second case when we use next function inside the middleware function.

Now we will start our server in command prompt

Next step we will check if the server responses back on user requesting on local server.

wow we got ouput.The server is responding.

Enjoy with this blogger.

If you like this Please follow my publication to get more blogs on javascript and nodeJs.

--

--