Backend Development

What Is Middleware in Express.js? A Beginner-Friendly Guide

Imagine you're building a login system for your website. Whenever a user tries to access their profile, you need to check whether they are logged in. You might…

D
DevByteTechnical Author
Published
8 min read0 views
What Is Middleware in Express.js? A Beginner-Friendly Guide

Imagine you're building a login system for your website. Whenever a user tries to access their profile, you need to check whether they are logged in. You might also want to log every incoming request, validate user input, and handle errors consistently.

Now imagine writing the same logic separately for every route in your application. Your code would quickly become repetitive, difficult to maintain, and unnecessarily complicated.

What if you could execute specific functions before a request reaches its final route handler?

That's exactly where middleware in Express.js becomes useful.

Middleware is one of the most important concepts in Express.js because it helps developers organize backend logic, handle requests efficiently, implement authentication, and build maintainable APIs.

Whether you're learning Node.js or developing applications with the MERN stack, understanding middleware will help you write cleaner and more professional backend code.

Let's understand how it works with practical examples.

What Is Middleware in Express.js?

Middleware in Express.js is a function that has access to the request object (req), the response object (res), and the next() function.

Middleware functions can execute code, modify request or response objects, end the request-response cycle, or pass control to the next middleware or route handler.

In simple terms, middleware works like a checkpoint between a client's request and the server's final response.

For example, when a user sends a request to your API, middleware can:

  • Log information about the request.

  • Check whether the user is authenticated.

  • Validate incoming data.

  • Parse JSON request bodies.

  • Apply security-related checks.

  • Handle errors.

Instead of repeating these operations inside every route, you can create middleware functions and reuse them wherever necessary.

A Simple Example of Middleware

Let's create a basic Express.js application with middleware.

const express = require("express");

const app = express();

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

app.get("/", (req, res) => {
  res.send("Welcome to my website!");
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

When you visit http://localhost:3000, the middleware runs before the route handler sends the response.

The terminal displays:

Middleware executed

The browser displays:

Welcome to my website!

Let's understand the important parts:

  • app.use() registers middleware for matching requests.

  • req contains information about the incoming request.

  • res is used to send a response to the client.

  • next() passes control to the next applicable middleware or route handler.

Important: If middleware neither sends a response nor calls next() or otherwise transfers control appropriately, the request may remain pending.

How Does Middleware Work in Express.js?

Middleware follows a request-processing flow.

Consider this example:

Client Request → Logger Middleware → Authentication Middleware → Route Handler → Response

Here's what happens at each stage:

Step 1: The client sends a request.

A user requests a protected endpoint, such as /profile.

Step 2: Logger middleware runs.

The middleware records details about the incoming request, such as its HTTP method and URL.

Step 3: Authentication middleware runs.

The middleware checks whether the request contains valid authentication credentials.

Step 4: The route handler executes.

If authentication succeeds, the request reaches the route handler, which processes the requested operation.

Step 5: The server sends a response.

The client receives the requested data or an appropriate error response.

If authentication fails, the middleware can return a 401 Unauthorized response without allowing the request to reach the protected route.

This approach separates different responsibilities and makes your backend easier to maintain.

Types of Middleware in Express.js

Express.js supports several types of middleware. Understanding them will help you decide where and how to use each one.

1. Application-Level Middleware

Application-level middleware is registered using app.use() or methods such as app.get() and app.post().

For example:

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

This middleware runs for requests that match its registration scope and position in the middleware stack.

Because it is registered at the application level, you can use it to handle common tasks across multiple routes.

Common use cases:

  • Request logging.

  • Adding common request-processing logic.

  • Tracking request duration.

  • Setting response headers.

2. Router-Level Middleware

Router-level middleware works similarly to application-level middleware, but it is attached to an Express router.

This is particularly useful when your application has multiple modules, such as users, products, and orders.

const express = require("express");

const router = express.Router();

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

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

module.exports = router;

You can mount this router in your main application:

const userRoutes = require("./routes/userRoutes");

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

Now the router handles requests under /api/users, and its middleware runs according to the router's configuration.

Router-level middleware helps keep large applications modular and organized.

3. Built-in Middleware

Express.js includes built-in middleware for common tasks, so you don't need to install separate packages for everything.

One of the most commonly used examples is express.json().

app.use(express.json());

app.post("/api/users", (req, res) => {
  console.log(req.body);

  res.status(201).json({
    message: "User received",
    user: req.body
  });
});

When a client sends a JSON request body with the appropriate content type, express.json() parses it and makes the resulting data available through req.body.

Without suitable parsing middleware, req.body may be undefined.

Other useful built-in middleware includes:

  • express.urlencoded() — Parses URL-encoded request bodies.

  • express.static() — Serves static files such as images, CSS, and JavaScript files.

4. Third-Party Middleware

Third-party middleware is created by external developers and installed through npm.

For example, cors helps configure Cross-Origin Resource Sharing, while morgan provides HTTP request logging.

Install the packages:

npm install cors morgan

Use them in your application:

const cors = require("cors");
const morgan = require("morgan");

app.use(cors());
app.use(morgan("dev"));

The morgan("dev") middleware logs incoming HTTP requests in a developer-friendly format.

The cors() middleware configures CORS behavior. In production, configure its allowed origins and other options according to your application's requirements rather than automatically allowing every origin.

5. Error-Handling Middleware

Error-handling middleware is used to handle errors that occur during request processing.

Unlike regular middleware, it accepts four arguments: err, req, res, and next.

app.get("/api/data", (req, res, next) => {
  try {
    throw new Error("Something went wrong");
  } catch (error) {
    next(error);
  }
});

app.use((err, req, res, next) => {
  console.error(err.message);

  res.status(500).json({
    message: "Internal server error"
  });
});

When next(error) is called, Express passes control to error-handling middleware.

Notice that the error handler is registered after the route. Middleware order matters, and error handlers should generally be placed after the routes and middleware whose errors they handle.

For asynchronous operations, make sure errors are forwarded correctly. Express 5 automatically forwards rejected promises returned by route handlers and middleware, while Express 4 generally requires explicit forwarding or an appropriate wrapper.

What Is the Difference Between next() and next(error)?

This is a common interview question for Node.js developers.

Feature

next()

next(error)

Purpose

Passes control to the next applicable middleware or route handler

Passes control to error-handling middleware

Typical use

Normal request processing

Error handling

Example

next()

next(new Error("Failed"))

For example:

app.use((req, res, next) => {
  if (!req.headers.authorization) {
    return res.status(401).json({
      message: "Authorization required"
    });
  }

  next();
});

If the authorization header is missing, the middleware sends a response and stops the normal processing flow.

If the header exists, it calls next() to continue processing.

However, checking whether an authorization header exists does not prove that the user is authenticated. A real authentication middleware must validate the supplied credentials, such as a session or token, before granting access.

Real-World Example: Authentication Middleware

Suppose you're building a blog application where only authenticated users can create articles.

Instead of checking authentication separately in every route, you can create reusable middleware.

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

  if (!token) {
    return res.status(401).json({
      message: "Please log in first"
    });
  }

  // Validate the token or session here.
  // Continue only after successful verification.

  next();
}

You can apply this middleware to a protected route:

app.post("/api/posts", authenticateUser, (req, res) => {
  res.status(201).json({
    message: "Post created successfully"
  });
});

In this simplified example, the authentication middleware illustrates where verification belongs. It is not production-ready until the token or session is actually validated and the authenticated user's identity is established.

This pattern allows you to reuse authentication logic across multiple protected routes without duplicating the same checks.

Common Middleware Mistakes to Avoid

Even experienced developers can make mistakes when working with middleware. Keep these points in mind:

1. Forgetting to call next(): If middleware doesn't send a response or transfer control, the request may hang.

2. Calling next() after sending a response: This can cause duplicate responses or errors. Return after sending a response when appropriate.

3. Registering middleware in the wrong order: Middleware runs according to its position in the stack. For example, JSON parsing middleware should normally be registered before routes that need req.body.

4. Trusting unvalidated input: Data in req.body, req.params, and req.query should be validated before it is used.

5. Treating middleware as a replacement for authorization: Authentication establishes who the user is; authorization determines what that user is allowed to do.

Avoiding these mistakes will help you build safer and more reliable Express.js applications.

Conclusion

Middleware is a fundamental part of Express.js that allows developers to process HTTP requests through reusable functions before sending responses.

From logging requests and parsing JSON to implementing authentication and handling errors, middleware makes backend applications more organized, flexible, and maintainable.

If you're learning Express.js, start by creating a simple logging middleware. Then experiment with built-in middleware, router-level middleware, and authentication checks.

Once you understand how middleware works and how execution order affects requests, you'll find it much easier to build structured REST APIs and real-world Node.js applications.

Remember: Middleware isn't just another Express.js feature. It's one of the key tools that helps you turn a collection of routes into a well-organized backend application.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘