Writing custom middleware functions in NodeJS

Middleware is any code that runs on the server between getting a request and a response. Middleware functions in NodeJS have access to the request object, the response object, and the next function.

function middleFunc(req,res,next){

In the example above, the function middleFunc is a middleware function that takes three parameters: req,res,and next. The function sets a req.message to 'Hello'.

Middleware functions do not end the request-response cycle but they have to call next() to either pass execution to the next middleware function or the request handler itself. If next() function is not called, the request will hang.

A middleware function can be run by passing it between the path and callback function of the request handler.


Here, middleFunc will run first then when next() is called, the execution is passed to the request handler which prints the message.

It is also possible to rewrite the middleware function as an Application-level middleware like this,

    req.message = 'Hello'