Skip to main content

Command Palette

Search for a command to run...

What is Middleware in Express and How It Works (Complete Guide)

Updated
4 min read
What is Middleware in Express and How It Works (Complete Guide)
A

i am learner whatever i will learn i will write here

Introduction

When building backend applications using Express.js, one concept you’ll use everywhere is:

Middleware

Middleware is the backbone of Express apps — it controls how requests are processed before sending a response.

In this guide, you’ll learn:

  • What middleware is

  • Where it fits in request lifecycle

  • Types of middleware

  • Execution order

  • Role of next()

  • Real-world use cases


What is Middleware?

Middleware is a function that runs between request and response

Simple Definition:

Middleware acts like a checkpoint that processes a request before it reaches the final route.


Request Lifecycle (Big Picture)

https://images.openai.com/static-rsc-4/uLrbyqxbXl5gZI-8GUKV8IOEDC5EB9SRI_TCR94K2-HzhWe79345miNOobmJa2JjIgXj3Ro8Oqse7kZp44VbYoiDo6COkkEBBDscLL5qhtHOxHd0stz9TLfrADMoFTfU93PfSIZwNcYegmat5oGX8-93ylRPXHebcpzd823kOs1JvkAB2INrhmAHS4HjPjuy?purpose=fullsize

Flow:

Client Request → Middleware → Route Handler → Response

Middleware as a Pipeline

Think of it like:

Request travels through checkpoints

Each middleware can:

  • Modify request

  • Stop request

  • Pass to next


Basic Middleware Example

import express from "express";

const app = express();

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

// Route
app.get("/", (req, res) => {
  res.send("Hello World");
});

app.listen(3000);

Output in console:

Middleware executed

Types of Middleware in Express


Application-Level Middleware

Applied to entire app

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

Runs for all routes


Router-Level Middleware

Applied to specific routes

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

Runs only for /user


Built-in Middleware

Express provides built-in middleware:

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

Used for:

  • Parsing JSON

  • Handling form data


Execution Order of Middleware

Middleware runs in the order you define it

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

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

Output:

First
Second

Middleware Chain Execution

https://images.openai.com/static-rsc-4/qYU4zjr21xitdEHj987J8mIM7c4BS30pxJC4w6wPIoOWzosBeZrkNBe9yQOKq2jydZSFypcXB5atrTchRlOHjzRUmARuF_qQURIJf965VV3DXVhkw8SEK2UpLvZ_Ek3J8PxEDbKVQMnFc1EhBuKFwfnH2KZ0oGCI8lXnDsn4xEU1MlOX00rGTW-TR2_TSqwq?purpose=fullsize https://images.openai.com/static-rsc-4/-Olb5sAqCD-L6UFoU0yPfd11BFT0KthRGgEfc2iqqmOZz5w1_rNelncFzuoBqg5VWXw17fNSkmmLQMnAgQ4Y4zLoUulru4W9-3tV1j4XM7maw5iz3INCDIi5wul7e8MUbGfNr9YGWuU9uYDPC7ZAxqG-nu8DfisnY2nwtOcjfG4R8cJreZngZTi1Kiqf-Mv7?purpose=fullsize

Flow:

Request → Middleware 1 → Middleware 2 → Middleware 3 → Route

Role of next() Function

next() is VERY IMPORTANT

It tells Express:

“Move to the next middleware”


Without next()

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

Request will hang


With next()

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

Request continues


Real-World Middleware Examples


1. Logging Middleware

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

Tracks requests


2. Authentication Middleware

app.use((req, res, next) => {
  const isLoggedIn = true;

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

  next();
});

Protects routes


3. Request Validation

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

Ensures correct data


Common Beginner Mistakes

Forgetting next() Request gets stuck

Wrong order of middleware Logic breaks

Overusing middleware

Makes app confusing


Best Practices

  • Keep middleware small & focused

  • Use separate files for large apps

  • Always call next() (unless sending response)

  • Order matters — plan carefully


Simple Analogy (Easy to Remember)

Think of middleware like airport security

  • Passenger = Request

  • Security checks = Middleware

  • Boarding = Route handler

Each checkpoint verifies before moving ahead


Conclusion

Now you understand:

✔ What middleware is

✔ Where it sits in lifecycle

✔ Types of middleware

✔ Execution order

✔ Importance of next()

✔ Real-world usage

More from this blog

W

WEB DEV COHORT 2K26

24 posts

I share easy-to-understand blogs on JavaScript, Backend Development, and DSA.

From basics to real-world concepts — everything explained simply 🚀