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

When you build a web application using Express.js, every request from the user goes through a process before reaching the final response. In this process, middleware plays a very important role.

Middleware helps us handle requests step by step, like a checkpoint system between request and response.

What is Middleware in Express?

Middleware is a function in Express that runs between the request and response cycle.

It can access the request, response, and move the request to the next step.

It can:

  • Modify request data

  • Log information

  • Check authentication

  • Stop or continue requests

Middleware as a Checkpoint

Think of middleware like a security checkpoint at an airport:

  • You cannot directly go to the plane

  • You must pass through security checks

  • Each checkpoint verifies something

Similarly:

Request → Middleware → Middleware → Route → Response


Where Middleware Sits in Request Lifecycle

In Express, the flow is:

Client Request 
      ↓ 
Middleware functions 
      ↓ 
Route handler 
      ↓ 
Response sent back

Middleware always runs before the final route handler (unless stopped).

Basic Middleware Example

import express from 'express';
const app = express();

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

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

app.listen(3000);

Here:

  • Middleware logs request

  • next() moves execution forward


Role of next() Function

The next() function is very important.

It tells Express:

"Move to the next middleware or route"

If you forget next():

  • Request will stop

  • Response will not be sent

  • App may hang or crashed

Example:

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

Types of Middleware in Express

There are mainly 3 types of middleware:

1. Application-Level Middleware

This middleware is applied to the entire app.

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

Used for:

  • Logging

  • Authentication

  • Request tracking

2. Router-Level Middleware

This middleware works only for specific routes.

const router = express.Router();

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

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

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

Used for:

  • Grouped routes

  • Module-based apps

3. Built-in Middleware

Express provides some built-in middleware.

app.use(express.json());

This is used to parse JSON request bodies.

Other built-in middleware:

  • express.urlencoded()

  • express.static()


Real-World Use Cases of Middleware

Middleware is used in almost every web application.

1. Logging Middleware

Used to track requests.

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

Output: GET /home

2. Authentication Middleware

Used to protect routes.

function auth(req, res, next) {
  let loggedIn = true;

  if (!loggedIn) {
    return res.send("Access Denied");
  }

  next();
}

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

Only logged-in users can access dashboard.

3. Request Validation Middleware

Used to check input data.

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

Why Middleware is Important

  • Keeps code organized

  • Reusable logic

  • Separates concerns

  • Controls request flow

  • Improves security


Conclusion

Middleware is one of the most powerful concepts in Express.js. It works as a bridge between request and response and allows developers to control how requests are processed.

Without middleware, building scalable backend applications would be much harder.

Middleware makes Express.js flexible, structured, and powerful by allowing multiple processing steps before sending a response.