Lesson 18 +10 XP

Understanding the Middleware Stack & next()

What is Middleware?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application's request-response cycle.

The Role of next()

The next() function is a callback that passes control to the next middleware function in the stack. If a middleware function does not end the request-response cycle (e.g. by calling res.send() or res.json()), it must call next() to avoid leaving the request hanging.

const express = require("express");
const app = express();

// Application-level middleware 1: Request Logger
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next(); // Pass execution to next middleware
});

// Application-level middleware 2: Request Timestamp
app.use((req, res, next) => {
  req.requestTime = Date.now();
  next();
});

app.get("/time", (req, res) => {
  res.json({ requestTime: req.requestTime });
});

Middleware Execution Order

⚠️ DocHero Safety Disclaimer

Middleware functions execute in the exact order they are registered using app.use() or route definitions. Always register body parsers and request loggers before route handlers!

TL;DR

  • Middleware sits between request arrival and response sending.
  • Call next() to pass control down the pipeline.
  • Forgetting to call next() or send a response causes client request timeouts.