# What is Middleware in Express and How It Works

## Introduction

When building backend applications using Express.js, one of the most important concepts you’ll encounter is **middleware**. Middleware is what gives Express its flexibility and power.

At a high level, middleware acts like a **checkpoint system** between a client request and the server response.

* * *

## What is Middleware in Express?

Middleware is simply a **function** that has access to:

*   `req` (request object)
    
*   `res` (response object)
    
*   `next` (function to pass control)
    

### Basic Syntax

```js
function middleware(req, res, next) {
  console.log("Middleware executed");
  next();
}
```

👉 Middleware can:

*   Modify request/response
    
*   End the request-response cycle
    
*   Call the next middleware
    

* * *

## Where Middleware Sits in the Request Lifecycle

Think of Express as a **pipeline**:

```plaintext
Client Request → Middleware → Middleware → Route Handler → Response
```

Each middleware processes the request step by step before reaching the final route handler.

### Example Flow

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

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

app.get("/", (req, res) => {
  res.send("Final Response");
});
```

### Execution Order

```plaintext
Step 1 → Step 2 → Route Handler → Response
```

* * *

## Types of Middleware in Express

### 1\. Application-Level Middleware

These are bound to the entire app using `app.use()`.

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

✔ Runs on every request (unless restricted by path)

* * *

### 2\. Router-Level Middleware

Used with Express routers (`express.Router()`).

```js
const router = express.Router();

router.use((req, res, next) => {
  console.log("Router middleware");
  next();
});

app.use("/api", router);
```

✔ Only runs for specific route groups (`/api` here)

* * *

### 3\. Built-in Middleware

Express provides some ready-made middleware:

*   `express.json()` → Parses JSON body
    
*   `express.urlencoded()` → Parses form data
    
*   `express.static()` → Serves static files
    

```js
app.use(express.json());
```

✔ Saves time—no need to write common logic manually

* * *

## Execution Order of Middleware

Middleware executes **in the order it is defined**.

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

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

Output:

```plaintext
First
Second
```

⚠️ Important: If `next()` is not called, the request **will hang**.

* * *

## Role of `next()` Function

`next()` is what **moves the request forward** in the pipeline.

### Without next()

```js
app.use((req, res, next) => {
  console.log("Stops here");
});
```

❌ Request never reaches route handler → client hangs

* * *

### With next()

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

✔ Execution continues

* * *

### Ending Response in Middleware

```js
app.use((req, res, next) => {
  res.send("Response from middleware");
});
```

✔ No need to call `next()` because response is already sent

* * *

## Real-World Examples of Middleware

### 1\. Logging Middleware

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

✔ Helps track incoming requests

* * *

### 2\. Authentication Middleware

```js
function auth(req, res, next) {
  const isLoggedIn = true;

  if (!isLoggedIn) {
    return res.status(401).send("Unauthorized");
  }

  next();
}

app.get("/dashboard", auth, (req, res) => {
  res.send("Welcome to dashboard");
});
```

✔ Protects routes

* * *

### 3\. Request Validation Middleware

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

app.post("/user", validate, (req, res) => {
  res.send("User created");
});
```

✔ Ensures clean and valid input

* * *

## Key Takeaways

*   Middleware = **functions between request and response**
    
*   They run **sequentially**
    
*   `next()` controls flow
    
*   You can stack multiple middleware
    
*   Used for **logging, auth, validation, parsing, etc.**
    

* * *

## Final Analogy

Think of middleware like **security checkpoints at an airport**:

*   Passport check → Security scan → Boarding gate
    
*   Each step verifies something before allowing you forward
    

Similarly:

```plaintext
Request → Middleware checks → Final Response
```

* * *

## Conclusion

Middleware is the backbone of Express applications. Once you understand how middleware flows and how `next()` works, you gain fine-grained control over request handling.

Mastering middleware is essential for building **scalable, maintainable backend systems**.
