Skip to content

Part 3a Middlewares #4215

@Rasmuzeri

Description

@Rasmuzeri

I found myself confused by the app.use statements. They looked like standard setup "imports" but their order actually matters. The question arises:

Why does Express not work "normally"?

The material explains what and how but not so much about the why.

Turns out, the whole architecture/workflow of Express was all along based on this "conveyor belt" design. You have to stop thinking of your code as a standard top-to-bottom program and start seeing it as a factory line.

When an HTTP request hits your server, it is like a raw chassis entering the factory. Each middleware is a station on that belt:

  1. express.json() is a station that takes the raw text and turns it into a JavaScript object, adding it to the request.body.
  2. morgan is a station that records the details of the request for logs.
  3. Your Routes are stations that look at the request and decide if they should finish the job and send a response back to the user.

Because it is a conveyor belt, order is everything. If you place a "Logger" station before the "JSON Parser" station, the logger will see an empty body because the data hasn't been bolted on yet. The request object is essentially a bucket moving down the line.

BUT WHY does it even have this conveyor belt design?

It’s because web servers deal with repetitive, global chores. Almost every request needs to be logged, checked for security, and parsed into JSON. Before Express and the "Middleware" pattern became popular, many frameworks required you to manually call these five or six setup functions at the start of every single route you wrote. If you had 50 routes, you had 50 places to accidentally forget a security check or a logging call. The creators of Express wanted to avoid this "boilerplate" nightmare. The conveyor belt automates the common lifecycle of a request. It ensures the "boring" work is done consistently and in the right order before the request ever reaches your specific business logic. Ohhh.

So maybe we could add something like that? Doesn't even have to be this long. I do understand some things have to be left for the reader to search about, but maybe this is important and fundamental enough. I don't know, you tell me

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions