Skip to main content

Command Palette

Search for a command to run...

Middleware: The Stuff Happening While You Think Nothing’s Happening

Updated
4 min read
Middleware: The Stuff Happening While You Think Nothing’s Happening
V

Hi, I'm Vishal Gupta, a passionate and self-driven Full-Stack Developer with a strong command of the MERN stack (MongoDB, Express.js, React.js, Node.js). I love turning complex problems into clean, scalable solutions through elegant code and user-friendly interfaces. With hands-on experience building real-world applications like MedEase, TripGenius, and now this Expense Tracker, I strive to build software that’s not only functional but also impactful. Whether it's creating secure authentication systems, responsive UI components, or integrating AI-powered features, I aim to deliver value with every line of code. 🔧 Key Skills: Frontend: React.js, Vite, Tailwind CSS, ShadCN, Context API Backend: Node.js, Express.js, MongoDB, JWT, REST APIs Dev Tools: Git & GitHub, Postman, Firebase, Vercel Soft Skills: Problem-solving, communication, and a strong desire to learn & grow I believe in continuous learning and building meaningful products that solve real-life problems. Currently, I’m open to opportunities where I can collaborate, innovate, and contribute to exciting web development projects.

Middleware is one of the most important concepts in Express.
If you understand middleware well, you understand how Express really works.

In simple words:

Middleware is just a function that runs between the request and the response.
It can check things, modify data, log activity, validate input, authenticate users, handle errors, and much more.

Let’s break it down step by step.


What Is Middleware?

Middleware is any function in Express that has access to:

  • req → the incoming request

  • res → the outgoing response

  • next() → a function that moves to the next middleware

A basic middleware looks like this:

app.use((req, res, next) => {
  console.log("A request came in");
  next();
});

Here:

  • The middleware logs a message

  • next() sends the request forward

  • Without next(), the request stops


Why Is Middleware Important?

Middleware helps you:

  • log requests

  • validate data

  • authenticate users

  • parse JSON

  • handle errors

  • restrict access

  • attach custom data to req or res

  • protect API routes

  • check permissions

  • handle uploaded files

Express itself is built entirely on middleware.


Types of Middleware in Express

There are several kinds, each useful for different tasks.


1. Application-Level Middleware

This middleware applies to the whole app.

app.use((req, res, next) => {
  console.log("Time:", Date.now());
  next();
});

Runs on every request.


2. Route-Level Middleware

You attach it to a specific route.

app.get("/users", (req, res, next) => {
  console.log("Users route hit");
  next();
}, (req, res) => {
  res.send("Users data");
});

Only runs for /users.


3. Router-Level Middleware

Used inside express.Router().

routes/userRoutes.js

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

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

router.get("/", (req, res) => {
  res.send("All users");
});

module.exports = router;

In server.js

app.use("/users", userRoutes);

Middleware runs only for /users/... routes.


4. Built-In Middleware

Express has some built-in middleware:

Parse JSON

app.use(express.json());

Parse URL-encoded form data

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

Serve static files

app.use(express.static("public"));

5. Third-Party Middleware

Useful packages built by others:

Morgan (logging)

const morgan = require("morgan");
app.use(morgan("dev"));

Cors

const cors = require("cors");
app.use(cors());

Helmet (security)

const helmet = require("helmet");
app.use(helmet());

These add important features easily.


Creating Your Own Custom Middleware

Custom middleware gives you full control.

Example: logging IP address

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

Example: blocking users without an API key

app.use((req, res, next) => {
  if (!req.query.apiKey) {
    return res.status(401).send("API key missing");
  }
  next();
});

You can build any logic you want here.


How Middleware Flows

Express processes middleware in the same order that you define it.

Example:

app.use(firstMiddleware);
app.use(secondMiddleware);
app.use(thirdMiddleware);

Request passes through:

  1. firstMiddleware

  2. secondMiddleware

  3. thirdMiddleware

If any middleware doesn’t call next(), everything stops.


Error-Handling Middleware (Very Important)

To catch errors, Express uses special middleware with four parameters:

app.use((err, req, res, next) => {
  console.error("Error:", err.message);
  res.status(500).send("Something broke");
});

This middleware only runs when an error is passed using:

next(new Error("Something failed"));

Useful for handling:

  • database errors

  • validation errors

  • unhandled exceptions


Middleware in Routers (Cleaner Structure)

Using middleware inside routers keeps apps scalable.

routes/blogRoutes.js

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

// router-level middleware
router.use((req, res, next) => {
  console.log("Blog section accessed");
  next();
});

router.get("/", (req, res) => {
  res.send("All blogs");
});

module.exports = router;

Connect it:

app.use("/blogs", blogRoutes);

Summary

Middleware is the heart of Express.
It helps your app:

  • process requests

  • validate data

  • add security

  • authenticate users

  • log actions

  • handle errors

  • organize logic cleanly

Everything in Express flows through middleware.

Once you understand middleware well, you can build more professional, scalable, and maintainable APIs.

Thank you for reading till the end. I am grateful.

If you see any errors or face any difficulty in the blog,
Do let me know through comments or write to me on this
abhimanyug987@gmail.com

More from this blog

Backend Scratch

13 posts

This blog is about all the learnings I gather in the backend development journey through online tutorials & youtube videos.