Skip to main content

Command Palette

Search for a command to run...

What is Middleware in Express and How It Works

Updated
β€’3 min read
What is Middleware in Express and How It Works
S

Like to study,fitness freak,my looks is my first priority, hardworking person, like discipline and love to learn new thing

πŸš€ Introduction

When a request hits your Express server, it doesn’t go directly to the route handler.

πŸ‘‰ It passes through multiple checkpoints first β€” these are called middleware

Middleware is one of the most important concepts in Express πŸ”₯


🧠 What Is Middleware?

Middleware is:

πŸ‘‰ A function that runs between the request and the response

It can:

  • Modify request (req)

  • Modify response (res)

  • End the request

  • Pass control to the next function


🧩 Simple Analogy: Request Pipeline

Think of middleware like a pipeline 🚰

Request β†’ Middleware β†’ Middleware β†’ Route Handler β†’ Response

πŸ‘‰ Each step can inspect or modify the request


πŸ“Š Diagram Idea: Middleware Flow

Client β†’ Request β†’ Middleware β†’ Route β†’ Response

βš™οΈ Where Middleware Sits

Middleware sits:

πŸ‘‰ Between incoming request and final response

app.use((req, res, next) => {
  console.log("Middleware executed");
  next();
});

πŸ”„ Role of next() Function

πŸ‘‰ next() passes control to the next middleware

app.use((req, res, next) => {
  console.log("Step 1");
  next();
});

πŸ‘‰ Without next() β†’ request will hang ❌


πŸ“Š Diagram Idea: Execution Chain

Middleware1 β†’ Middleware2 β†’ Middleware3 β†’ Route

🧠 Types of Middleware


1️⃣ Application-Level Middleware

Applied to the whole app:

app.use((req, res, next) => {
  console.log("App-level middleware");
  next();
});

2️⃣ Router-Level Middleware

Applied to specific routes:

app.get("/user", (req, res, next) => {
  console.log("Route middleware");
  next();
}, (req, res) => {
  res.send("User route");
});

3️⃣ Built-in Middleware

Provided by Express:

app.use(express.json());

πŸ‘‰ Parses JSON request body


βš™οΈ Execution Order of Middleware

πŸ‘‰ Middleware runs in the order it is defined

app.use((req, res, next) => {
  console.log("First");
  next();
});

app.use((req, res, next) => {
  console.log("Second");
  next();
});

πŸ‘‰ Output:

First
Second

🌍 Real-World Examples


1️⃣ Logging Middleware

app.use((req, res, next) => {
  console.log(`\({req.method} \){req.url}`);
  next();
});

2️⃣ Authentication Middleware

function auth(req, res, next) {
  if (req.headers.token) {
    next();
  } else {
    res.send("Unauthorized");
  }
}

3️⃣ Request Validation

function validate(req, res, next) {
  if (!req.body.name) {
    return res.send("Name required");
  }
  next();
}

🧠 Conceptual Understanding

πŸ‘‰ Middleware = Gatekeeper πŸšͺ πŸ‘‰ It checks and processes requests before reaching the final handler


🏁 Conclusion

Middleware is the backbone of Express applications.

It helps you:

  • Organize logic

  • Reuse code

  • Control request flow


✨ Final Tip

If your logic repeats across routes β†’ make it middleware 😎