What is middleware in the context of Nodejs

middleware in nodejs

Developers who are new to Express often get confused with the difference between route handler and middleware. therefore they also get confused with the difference between following
a. app.use()
b. app.all()
c. app.get()
d. app.post()
e. app.delete() 
app.put() methods.

Middlewares are often used in the context of the Express.js framework and are a fundamental concept for node.js. In a nutshell, It's basically a function that has access to the request and response objects of your application. The way I'd like to think about it is a series of 'checks/pre-screens' that the request goes through before it is handled by the application.

For e.g, Middlewares would be a good fit to determine if the request is authenticated before it proceeds to the application and returns the login page if the request is not authenticated or for logging each request. A lot of third-party middlewares are available that enables a variety of functionality.

Middleware functions can perform the following tasks:
  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.
Simple Middleware example: 

  • var app = express();
  • app.use(function(req,res,next)){
  • console.log("Request URL - "req.url);
  • next();
  • }

  • The above code would be executed for each request that comes in and would log the request URL, the next() method essentially allows the program to continue. If the next() function is not invoked, the program would not proceed further and would halt at the execution of the middleware. 

    A couple of Middleware Gotchas:

    • The order of middlewares in your application matters, as the request would go through each one in a sequential order
    • Forgetting to call the next() method in your middleware function can halt the processing of your request
    • Any change the req and res objects in the middleware function would make the change available to other parts of the application that uses req and res

    A default express app usually comes with a set of middlewares to make request handling easier. 


    Post a Comment

    1. Kanhasoft is the top-notch Node.js App development company in India. We have 45+ experienced programmers to delivered successful NodeJS Application development globally. Visit our site to know more about us.

    Post a Comment