What is Express.js middleware?

Overview

Middleware functions in Express.js are used to provide extra functionality to the framework. Middleware has access to the request (req) and response (res) objects, which it uses to execute commands during the request-response cycle. Overall, it can serve the following purposes:

  • Execute arbitrary code
  • Call the next middleware function using the next() command
  • Make changes to the req and res objects
  • End the request-response cycle
Developers can either build their own middleware functions or utilize third-party tools fo the same tasks. A list of third-party middleware is available here.
Information flow in a client-server architecture using Express.js middleware

Syntax

{
  "name": "node-express-middleware",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "PORT=3000 node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^2.3.4",
    "express": "^4.13.3"
  }
}
Various types of middleware functions in a simple web application

Explanation

The example given above shows the application level, router level, and error handling middleware. The key difference between application-level middleware and router-level middleware is that the former is bound to an application object and the latter is bound to a router object. If a fourth argument is passed to the function, it is automatically considered an error-handling middleware.

The next() function is used to invoke the next appropriate middleware function. If this function is not called and the request-response cycle is not ended, then the request will be left hanging.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved