Understand Express Middleware

Middleware functions are functions that execute during the request-response lifecycle.

A middleware function receives three important arguments:

(req, res, next)
  • req: Contains incoming request information.
  • res: Provides methods for sending the response.
  • next: Passes control to the next middleware.

Middleware can:

  • Read request information.
  • Modify request or response objects.
  • Perform authentication.
  • Validate input.
  • Log requests.
  • Handle errors.
  • Terminate requests by sending responses.

If middleware neither sends a response nor calls next(), the request may remain pending.

Middleware order matters because Express executes middleware in registration order.

Express Middleware Execution
Create a Request Logging Middleware
function requestLogger(req, res, next) {
  console.log({
    method: req.method,
    path: req.originalUrl,
    timestamp: new Date().toISOString()
  });

  next();
}

app.use(requestLogger);

Logs incoming request information and passes execution to the next middleware.

Key Takeaways
  • Middleware executes during the request-response lifecycle.

  • next() passes execution to the next middleware.

  • Middleware order determines execution order.