Complete 2024 Web Development Bootcamp

Dr. Angela Yu

Back to Express Index


Express Middleware
Middleware

Express middleware refers to functions that process requests before reaching the route handlers. These functions can modify the request and response objects, end the request-response cycle, or call the next middleware function. Middleware functions are executed in the order they are defined. They can perform tasks like authentication, logging, or error handling. Middleware helps separate concerns and manage complex routes efficiently.

What Middleware Does in Express.js
Middleware functions in Express.js can perform several important tasks:

  1. Execute Code: Middleware can run any code when a request is received.
  2. Modify Request and Response: Middleware can modify both the request (req) and response (res) objects.
  3. End the Request-Response Cycle: Middleware can send a response to the client, ending the cycle.
  4. Call the Next Middleware: Middleware can call next() to pass control to the next function in the middleware stack.

How Middleware Works in Express.js?
In Express.js, middleware functions are executed sequentially in the order they are added to the application. Here’s how the typical flow works:

  1. Request arrives at the server.
  2. Middleware functions are applied to the request, one by one.
  3. Each middleware can either:
    • Send a response and end the request-response cycle.
    • Call next() to pass control to the next middleware.
  4. If no middleware ends the cycle, the route handler is reached, and a final response is sent.

Types of Middleware
ExpressJS offers different types of middleware and you should choose the middleware based on functionality required.

  1. Application-level Middleware
  2. Router-level Middleware
  3. Error-handling Middleware
  4. Built-in Middleware
  5. Third-party Middleware

More information can be found here.


Back to Top