Express Middleware

Middleware functions are functions that have access to the Request object, theResponse object, and the next function in the application’s request-response cycle.

The "next()" function: If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

1. Types of Middleware

  1. Application-level: Bound to the app object using app.use().
  2. Router-level: Bound to an instance of express.Router().
  3. Built-in: Provided by Express (e.g., express.json()).
  4. Third-party: Installed via NPM (e.g., morgan, cors).

2. Custom Middleware Example

Let's create a simple logger middleware that prints the time of every request.

const logger = (req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next(); // Don't forget this!
};

app.use(logger); // Applies to ALL routes

3. Built-in Middleware

Most Express apps need some built-in middleware to handle incoming data.

// Parse JSON payloads
app.use(express.json());

// Parse URL-encoded bodies (form data)
app.use(express.urlencoded({ extended: false }));

// Serve static files (images, css, js)
app.use(express.static('public'));

4. Middleware Order Matters

Middleware functions are executed in the order they are defined. If you define a logger after a route, it won't run for that route!