Express.js Mastery / Express: Let’s Start Building The Natours API!

Middleware and the Request-Response Cycle

🌐 Middleware & the Request-Response Cycle

With routing basics out of the way, it's time to understand how Express actually works under the hood. Middleware and the request-response cycle aren't just another topic β€” they're the core mental model behind everything else in Express.


πŸ“₯ The Big Picture

  1. A request hits the server.

  2. Express creates a request object and a response object.

  3. That data needs to be processed to generate a meaningful response.

  4. Express processes it using middleware.


🧩 What Is Middleware?

A middleware is simply a function that sits between the request coming in and the response going out. It can:

  • Modify the request object

  • Modify the response object

  • Run any other logic

You've actually already used middleware without calling it that β€” express.json() (aka body-parser) is a classic example; it's what gives you access to the request body. Logging, setting headers, authentication β€” all of it is middleware. The possibilities are endless.

⭐ Key insight: Even route handlers are middleware β€” just ones that only run for specific routes.


πŸ“š The Middleware Stack

All of an app's middleware functions, taken together, form the middleware stack.

⚠️ Critical rule: Middleware runs in the exact order it's defined in your code. Whatever's defined first, runs first. This makes code order genuinely important in Express.


πŸ”„ How a Request Flows Through the Stack

Think of it as a pipeline:

  1. The request/response objects are created.

  2. They pass through each middleware function one at a time, in definition order.

  3. Every middleware gets access to three things: req, res, and next.

  4. Calling next() hands off the same req/res objects to the next middleware in line.

  5. This repeats until the stack is exhausted.

The last middleware is typically the route handler β€” and it's different: instead of calling next(), it sends the response and ends the cycle.

That entire flow β€” request in, through every middleware, response out β€” is the request-response cycle.


βœ… Key Takeaway

  • Middleware = any function with access to req, res, and next, running between request and response.

  • Execution order = code order. Always.

  • next() passes the same req/res forward to the next function in the stack.

  • Route handlers are just the final middleware β€” they send the response instead of calling next().

  • This pipeline mental model is what makes express.json() (and Express generally) finally click.