Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

expressjs
node.js
javascript

What is Express.js middleware?

Rumaisa Habib

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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"
  }
}

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.

RELATED TAGS

expressjs
node.js
javascript

CONTRIBUTOR

Rumaisa Habib
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring