๐น What is Middleware?
Middleware is a piece of code that sits between two layers in a system and processes data or requests as they pass through.
It typically sits between the client request and the final server response.
You can think of it as a pipeline of functions that modify, filter, or inspect requests/responses before reaching the final destination.
๐น Analogy:
Imagine youโre entering a secured building.
At the gate: a guard checks your ID โ
At reception: someone logs your name ๐
On the way to the room: security scans your bag ๐
These checks are like middlewares โ each performs a task before you reach your destination.
๐น In Web Development (Node.js / Express Example):
In Express (a Node.js framework), middleware functions handle tasks like:
-
Logging
-
Authentication
-
Parsing JSON / forms
-
Error handling
-
CORS configuration
Example:
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass control to the next middleware
});Every req goes through this function before reaching the final route handler.
๐น Middleware Flow (Simplified):
-
Client sends request โ
-
Middleware 1 runs (e.g., logger)
-
Middleware 2 runs (e.g., auth check)
-
Route handler runs (e.g., return JSON)
-
Response goes back to client
If any middleware blocks or returns a response early, the rest are skipped.
๐น Types of Middleware:
| Type | Purpose |
|---|---|
| Application-level | Defined at the app level (e.g., app.use(...)) |
| Router-level | Applied only to certain routes |
| Error-handling | Catch and format server errors |
| Built-in | Like express.json() |
| Third-party | Like cors, helmet, morgan |
๐น Not Just Web:
Middleware is a general concept used in:
-
Operating systems (OS middleware between hardware and apps)
-
Microservices (API gateway is middleware)
-
Databases (connection poolers, proxies)