Loading...

Understanding Middleware in Express.js – A Complete Guide with Examples

Understanding Middleware in Express.js – A Complete Guide with Examples

Jeevan Singh

25 September, 2025

Express.js Logo


When working with Node.js and Express, you’ll frequently come across the term middleware. Middleware is at the heart of Express applications, making it possible to handle requests, responses, errors, authentication, logging, and much more. In this blog, we’ll break down what middleware is, why it’s important, and how you can use it effectively in your Node.js projects.

What is Middleware in Express?

In simple terms, middleware functions are functions that have access to the request (req), response (res), and the next function in the Express request-response cycle. They sit between the request and response and can perform tasks like:

  • Logging requests
  • Checking authentication
  • Validating user input
  • Handling errors
  • Modifying request/response objects

The next() function is crucial — it passes control to the next middleware in the stack. Without it, the request may hang.

Types of Middleware

1. Built-in Middleware

Express provides some middleware out of the box, such as:

app.use(express.json());      // Parse JSON bodies
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded data

These are essential for handling form data and JSON payloads in modern APIs.

2. Third-party Middleware

Developers often use third-party middleware from npm to simplify common tasks:

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

app.use(morgan('dev'));  // Logging requests
app.use(cors());         // Enable Cross-Origin Resource Sharing

This reduces boilerplate and improves maintainability.

3. Custom Middleware

You can also create your own middleware functions. For example, a simple logger:

function myLogger(req, res, next) {
  console.log(`Request made to: ${req.url}`);
  next(); // Pass control to the next middleware
}

app.use(myLogger);

Custom middleware is where the true power of Express shines, letting you control the flow of requests.

Middleware Use Cases

1. Authentication Middleware

You can protect routes by checking for a valid token before allowing access:

function authMiddleware(req, res, next) {
  const token = req.headers['authorization'];
  if (token === 'my-secret-token') {
    next();
  } else {
    res.status(401).json({ message: 'Unauthorized' });
  }
}

app.get('/dashboard', authMiddleware, (req, res) => {
  res.send('Welcome to your dashboard!');
});

2. Error Handling Middleware

Special middleware for error handling has four parameters: (err, req, res, next).

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

This ensures errors are caught and handled gracefully.

Best Practices

  • Always call next() unless you’re ending the request.
  • Use route-specific middleware for sensitive logic (like authentication).
  • Organize middleware into separate files for cleaner code.
  • Place error-handling middleware at the end of the middleware stack.

Conclusion

Middleware is one of the most powerful concepts in Express. By mastering it, you can add logging, authentication, validation, and error handling seamlessly into your applications. Whether using built-in, third-party, or custom middleware, understanding how it works will make you a far more effective Node.js developer.

RECENT POSTS

How E-Learning and EdTech Platforms Can Scale Using Microservices

Every edtech founder we’ve worked with at Speqto Technologies has faced the same 2 AM problem: the platform crashes right when 50,000 students log in for a live mock test, or the video server chokes during a scheduled webinar, or the payment gateway times out during a fee-payment rush before an admission deadline. If your […]

Why Regular Security Audits Matter for Banking-Adjacent Platforms

At Speqto Technologies, we’ve spent the last few years building and securing platforms that sit right next to banking rails — payment gateways, lending apps, wealth management dashboards, neobank front-ends. And if there’s one pattern we keep seeing, it’s this: companies invest heavily in their core product but treat security audits as a compliance checkbox […]

Choosing the Right Tech Stack for a Series A Fintech Startup

Once a fintech startup closes its Series A, the conversation in the boardroom shifts. It’s no longer just about proving the idea works — it’s about proving it can scale, survive an audit, and handle ten times the transaction volume without falling over. At Speqto Technologies, we’ve sat in on enough of these conversations with […]

How Kafka and Event-Driven Architecture Solve Data Sync Problems in BFSI Systems

Every BFSI or fintech platform we’ve worked with at Speqto Technologies eventually runs into the same wall: multiple systems — core banking, CRM, payment gateway, risk engine, notification service — all need the same piece of data, but they need it at different times, in different formats, and none of them trust the others to […]

Building Real-Time Dashboards for Operations and Compliance Teams: What Actually Works

A few months back, we sat in a review call with the ops head of a mid-sized NBFC. His complaint was simple: “By the time my team sees a problem in the report, the problem is already three hours old.” His compliance officer, sitting right next to him, had a similar issue — she was […]

POPULAR TAG

POPULAR CATEGORIES