Skip to content
BENIBIX Learn

Middleware

Development🌐 Web DevelopmentFrameworks

Also known as Web Middleware, Request Middleware, Middleware Function

Code that runs on each request, one step at a time, before the route gets it.

Think of it like

It is like the checks at an airport. Each person goes past the same desks to get to the gate.

Example

Emma adds a login check as middleware. Now each page under /account turns away people who are not signed in.

Why it matters

Jobs that each route needs are written once, not copied into each one. Logs, logins and limits often live here.

Definition

Middleware is code that runs on every request before your route answers it. Each piece does one job, then passes the request on. One might write a log line. Another might check the user is logged in. A piece can also stop the request early, like turning away a user with no login. Most web frameworks let you stack them in order.

Example code

javascript
app.use((req, res, next) => {
  console.log(req.method, req.url);
  next();
});
An Express middleware that logs each request, then hands it on with next().
Each box in the middle is middleware. The login check can stop a request early.

Common mistake

Forgetting to pass the request on. In Express that means calling next(), or the request hangs forever.

Key takeaways

  1. 1
    Runs on every request. Before the route gets it.
  2. 2
    One job each. Log, check, then pass it on.
  3. 3
    Order matters. The stack runs top to bottom.