# Middleware

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

**Field:** Software Development  
**Category:** Web Development  
**Also known as:** Web Middleware, Request Middleware, Middleware Function

## Think of it like

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

## 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

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

## 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().

## Why it matters

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

## Common mistake

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

## Three principles

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

## Related terms

- [Web Routing](https://learn.benibix.com/term/development/routing)
- [Express.js](https://learn.benibix.com/term/development/express)
- [FastAPI](https://learn.benibix.com/term/development/fastapi)
- [Authentication](https://learn.benibix.com/term/development/authentication)
- [Back End](https://learn.benibix.com/term/development/back-end)

![A request, GET /orders, passes left to right through two boxes, middleware 1 that logs it and middleware 2 that checks the login, then reaches the route, which gets the orders and sends a reply, 200 OK. A dashed arrow drops down from the login check to a box saying not logged in, stops here with 401.](https://learn.benibix.com/diagrams/dev-middleware.svg)

---

Source: https://learn.benibix.com/term/development/middleware
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
