๐Ÿ”น 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):

  1. Client sends request โ†’

  2. Middleware 1 runs (e.g., logger)

  3. Middleware 2 runs (e.g., auth check)

  4. Route handler runs (e.g., return JSON)

  5. Response goes back to client

If any middleware blocks or returns a response early, the rest are skipped.


๐Ÿ”น Types of Middleware:

TypePurpose
Application-levelDefined at the app level (e.g., app.use(...))
Router-levelApplied only to certain routes
Error-handlingCatch and format server errors
Built-inLike express.json()
Third-partyLike cors, helmet, morgan

๐Ÿ”น Not Just Web:

Middleware is a general concept used in: