Express.js Middleware

Express.js Middleware are different types of functions that are invoked by the Express.js routing layer before the final request handler. As the name specified, Middleware appears in the middle between an initial request and the final intended route. In stock, middleware functions are always invoked in the order in which they are added.

Middleware is commonly used to perform tasks like body parsing for URL-encoded or JSON requests, cookie parsing for basic cookie handling, or even building JavaScript modules on the fly.

What is a Middleware function?

Middleware functions are the functions that access the request and response object (req, res) in a request-response cycle.

A middleware function can perform the following tasks:

  • It can execute any code.
  • It can make changes to the request and the response objects.
  • It can end the request-response cycle.
  • It can call the next middleware function in the stack.

Express.js Middleware

Following is a list of possibly used middleware in the Express.js app:

  • Application-level middleware
  • Router-level middleware
  • Error-handling middleware
  • Built-in middleware
  • Third-party middleware

Let's take an example to understand what middleware is and how it works. Let's take the most basic Express.js app:


  var express = require('express');  
  var app = express();  
   
  app.get('/', function(req, res) {  
    res.send('Welcome to JavaTpoint!');  
  });  
  app.get('/help', function(req, res) {  
    res.send('How can I help You?');  
  });  
  var server = app.listen(8000, function () {  
    var host = server.address().address  
    var port = server.address().port  
  console.log("Example app listening at http://%s:%s", host, port)  
  })