Skip to main content

Command Palette

Search for a command to run...

What is Middleware in Express and How It Works ⚙️

Understanding the Request Pipeline in Node.js

Updated
4 min read
What is Middleware in Express and How It Works ⚙️

📌 Introduction

When a request hits an Express server, it doesn’t go directly to the response.

Instead, it passes through a series of steps.

👉 These steps are called middleware

Middleware is one of the most important concepts in Express.js because it controls how requests flow through your application.


🧠 What is Middleware in Express?

Middleware is:

A function that sits between the request and response cycle.


🧩 Simple Definition:

👉 Middleware = checkpoint in the request lifecycle

It can:

  • Read request data

  • Modify request/response

  • Stop or continue execution


🔄 Where Middleware Fits in the Request Lifecycle

Request → Middleware → Route Handler → Response

🧠 Key Idea:

Every request passes through middleware before reaching the final route.


⚙️ How Middleware Works

Middleware functions always receive 3 parameters:

(req, res, next)

🧠 Meaning:

  • req → request object

  • res → response object

  • next → moves to next middleware


🚀 The Role of next()

👉 next() is what keeps the request moving forward.


🧩 Example:

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

🧠 If you don’t call next():

👉 Request stops there ❌ 👉 No response continues


🧩 Types of Middleware in Express


1️⃣ Application-Level Middleware

Applied to the entire app.

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

🧠 Use Case:

  • Logging

  • Authentication checks

  • Global validation


2️⃣ Router-Level Middleware

Works on specific routes.

const express = require("express");
const router = express.Router();

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

router.get("/home", (req, res) => {
  res.send("Home Page");
});

module.exports = router;

🧠 Use Case:

  • Group-specific logic

  • Admin routes

  • User routes


3️⃣ Built-in Middleware

Express provides ready-made middleware.


🧩 Example:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

🧠 Use Case:

  • Parsing JSON data

  • Handling form submissions


🔄 Middleware Execution Order

Middleware runs top to bottom.


🧩 Example:

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

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

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

📦 Output:

First middleware
Second middleware

🔁 Middleware Execution Chain

Request
   ↓
Middleware 1
   ↓
Middleware 2
   ↓
Route Handler
   ↓
Response

🌍 Real-World Examples of Middleware


🧾 1. Logging Middleware

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

🧠 Purpose:

Track all incoming requests


🔐 2. Authentication Middleware

function auth(req, res, next) {
  const token = req.headers.authorization;

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

  next();
}

🧠 Purpose:

Protect routes


✅ 3. Request Validation Middleware

app.use((req, res, next) => {
  if (!req.body.name) {
    return res.status(400).send("Name is required");
  }

  next();
});

🧠 Purpose:

Ensure correct data


🍔 Request Pipeline Analogy

Imagine ordering food in a restaurant:

  1. You place an order

  2. Order goes through:

    • Reception

    • Kitchen check

    • Cooking

  3. Finally served

👉 Each step = middleware


⚠️ Important Concept

Middleware can:

  • End request (res.send)

  • Pass request (next)

  • Modify request (req)


🎯 Key Takeaways

  • Middleware sits between request and response

  • It executes in sequence

  • next() moves request forward

  • Types include application, router, and built-in middleware

  • Used for logging, auth, validation


✍️ Practice Challenge

Try building:

👉 Middleware that:

  • Logs time of request

  • Blocks requests without a header

  • Sends response if valid


🔥 Conclusion

Middleware is the backbone of Express.js request handling.

👉 It acts like a pipeline 👉 Controls request flow 👉 Makes apps modular and scalable

Once you understand middleware, building backend apps becomes much more structured and powerful 💪


Happy Coding ⚙️✨

How the Web Works 🕸️🕸️

Part 8 of 50

A practical web development series explaining how the web works—from DNS and browsers to servers, HTTP, APIs, and deployment—while clearly connecting these fundamentals to real-world website programming using frontend and backend examples.

Up next

JavaScript Promises Explained for Beginners ⚡

Understanding Asynchronous Code Without the Confusion