Backend Development

What Are the Different Types of Middleware in Express.js?

Imagine you're building a blog application using Node.js, Express.js, and MongoDB. Users can register, log in, publish articles, and leave comments. Everything…

D
DevByteTechnical Author
Published
7 min read0 views
What Are the Different Types of Middleware in Express.js?

Imagine you're building a blog application using Node.js, Express.js, and MongoDB. Users can register, log in, publish articles, and leave comments. Everything works well initially, but as your application grows, you start facing a problem.

You need to verify users before allowing them to publish articles, log every incoming request, validate submitted data, and handle errors consistently.

Writing this logic separately inside every route would make your code repetitive and difficult to maintain.

The solution? Middleware.

Middleware allows you to perform common operations during the request-response cycle without repeating the same logic across your application. However, Express.js supports different types of middleware, and each serves a particular purpose.

In this guide, we'll explore the five main categories of Express.js middleware, understand how they work, and learn when to use each one through practical examples.

What Is Middleware in Express.js?

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

It can execute code, modify the request or response, end the request-response cycle, or pass control to another middleware function.

For example:

const express = require("express");

const app = express();

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

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

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

Whenever a matching request reaches the server, the middleware logs the HTTP method and URL before passing control to the route handler.

Here, next() tells Express.js to continue processing the request.

Now that we understand the basics, let's explore the different types of middleware.

1. Application-Level Middleware

Application-level middleware is registered on an Express application instance using methods such as app.use() and app.get().

It is commonly used to execute logic across multiple routes.

For example, imagine you want to log every incoming request to your application. Instead of adding logging code to every route, you can register one middleware function.

const express = require("express");

const app = express();

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

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

app.get("/about", (req, res) => {
  res.send("About Page");
});

app.listen(3000);

Now, requests to both / and /about pass through the logging middleware.

When Should You Use Application-Level Middleware?

Use it when you need common functionality across your application, such as:

  • Logging incoming requests.

  • Parsing request bodies.

  • Setting common response headers.

  • Measuring request-processing time.

  • Applying shared request-processing rules.

Important: Application-level middleware follows registration order. If you register middleware after a route, it generally won't run for requests that have already been handled by that route.

2. Router-Level Middleware

Router-level middleware works similarly to application-level middleware, but it is attached to an instance of express.Router().

It is particularly useful for organizing large applications into separate modules.

Suppose your application has different sections for users, products, and orders. Each section may require its own middleware.

You can create a router for users:

const express = require("express");

const router = express.Router();

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

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

router.get("/:id", (req, res) => {
  res.json({ message: `User ID: ${req.params.id}` });
});

module.exports = router;

Then, register it in your main application:

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

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

Now, requests matching /api/users are handled by the user router, and its middleware runs according to the router's configuration.

For example:

  • GET /api/users retrieves the users list.

  • GET /api/users/10 retrieves information associated with user ID 10.

When Should You Use Router-Level Middleware?

Router-level middleware is useful when you want to:

  • Apply authentication checks to a particular module.

  • Log requests for specific routes.

  • Validate data before processing a request.

  • Keep route-specific logic separate from your main server file.

For medium-sized and large applications, router-level middleware helps maintain a cleaner project structure.

3. Built-in Middleware

Built-in middleware is provided directly by Express.js, so you don't need to install a separate npm package to use it.

Express.js includes several useful middleware functions for common backend tasks.

Let's look at the most important ones.

A. express.json()

This middleware parses incoming JSON request bodies.

app.use(express.json());

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

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

If a client sends a JSON request such as:

{
  "name": "Rahul",
  "email": "rahul@example.com"
}

Express.js parses the body, making the resulting object available through req.body when the request has the appropriate content type.

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

Remember to validate incoming data before using it in your application.

B. express.urlencoded()

This middleware parses incoming requests containing URL-encoded form data.

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

It is useful when your application receives traditional HTML form submissions.

The extended option controls how URL-encoded data is parsed.

C. express.static()

This middleware serves static files such as images, CSS files, JavaScript files, and HTML documents.

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

If your project contains an image at public/images/logo.png, it can be accessed through /images/logo.png.

Static middleware is useful when serving assets directly from your Express application.

4. Third-Party Middleware

Third-party middleware is developed outside Express.js and installed through npm.

Developers use it when they need functionality that is not included in Express's built-in middleware.

Popular examples include:

  • Morgan: Logs HTTP requests.

  • CORS: Configures Cross-Origin Resource Sharing.

  • Helmet: Helps set HTTP security headers.

  • Cookie-parser: Parses cookies attached to incoming requests.

Let's see how to use Morgan and CORS.

First, install the packages:

npm install morgan cors

Then, register them in your application:

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

const app = express();

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

app.use(cors({
  origin: "http://localhost:5173"
}));

app.get("/", (req, res) => {
  res.send("Express application is running");
});

app.listen(3000);

Here, Morgan logs incoming HTTP requests in a developer-friendly format.

The CORS middleware allows the configured frontend origin to make eligible cross-origin requests. Adjust the allowed origins and other CORS settings to match your application's deployment requirements.

When Should You Use Third-Party Middleware?

Use third-party middleware when you need established solutions for common tasks, such as request logging, CORS configuration, security headers, or cookie parsing.

Before installing a package, check whether it is actively maintained and whether its functionality fits your application's security requirements.

5. Error-Handling Middleware

Error-handling middleware is designed to process errors that occur during request handling.

Unlike regular middleware, it accepts four arguments:

(err, req, res, next)

Consider this example:

app.get("/api/profile", (req, res, next) => {
  try {
    throw new Error("Profile could not be loaded");
  } catch (error) {
    next(error);
  }
});

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

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

When an error occurs, next(error) passes control to Express.js error-handling middleware.

The error handler logs the error and returns a consistent response to the client.

Why Is Error-Handling Middleware Important?

Without centralized error handling, you may end up repeating similar error-response logic across many routes.

Error-handling middleware helps you:

  • Return consistent error responses.

  • Separate error handling from business logic.

  • Log unexpected failures.

  • Avoid exposing sensitive internal details to clients.

Place your error-handling middleware after the routes and middleware that may generate errors.

For asynchronous code, remember that Express 5 automatically forwards rejected promises returned by route handlers and middleware. In Express 4, you generally need to forward asynchronous errors explicitly or use an appropriate wrapper.

Bonus: How Middleware Types Work Together

In a real-world Express.js application, these middleware categories often work together.

For example, a blog API might use this request-processing flow:

Incoming Request → Request Logger → JSON Parser → Authentication Middleware → Route Handler → Error Handler (if needed)

Here's what each component does:

  1. The logger records information about the request.

  2. The JSON parser makes incoming JSON data available.

  3. Authentication middleware verifies the user's credentials when required.

  4. The route handler performs the requested operation.

  5. Error-handling middleware processes errors that are forwarded to it.

The exact order depends on your application's requirements. Public routes may not require authentication, while protected routes should enforce appropriate authentication and authorization checks.

Understanding middleware order is just as important as understanding the middleware types themselves.

Conclusion

Express.js provides different types of middleware to help developers organize request processing and build maintainable backend applications.

The five main categories are:

  1. Application-level middleware — Handles common application-wide operations.

  2. Router-level middleware — Applies logic to specific routers or route groups.

  3. Built-in middleware — Provides features such as JSON parsing and static file serving.

  4. Third-party middleware — Adds functionality through external packages.

  5. Error-handling middleware — Handles errors consistently.

Each category serves a different purpose, but they can work together to make your Express.js application more structured, reusable, and reliable.

If you're learning Node.js, start by creating a logging middleware, experiment with express.json(), and then build a simple authentication middleware for protected routes.

Once you understand how these components work together, you'll be better prepared to develop real-world REST APIs and scalable backend applications.

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↘