Back to Roadmap
5:00

Middleware in Express

Learn how middleware works in Express.js and how it helps manage requests, responses, and application logic efficiently

5 MIN READ VERIFIED CURRICULUM

Middleware is one of the most important concepts in Express.js used to process requests before sending responses.

It allows developers to execute custom logic during the request-response lifecycle.

What is Middleware?

Middleware functions are functions that have access to the request object, response object, and the next middleware function.

They can modify requests, execute code, validate data, or terminate the request-response cycle.

Middleware Function Syntax

const middleware = (req, res, next) => {
  console.log('Middleware Executed');
  next();
};
javascript

The next function passes control to the next middleware or route handler.

Why Middleware is Important

Middleware helps separate reusable logic from route handlers, making applications cleaner and easier to maintain.

It is commonly used for authentication, logging, validation, and error handling.

Using Middleware Globally

Global middleware executes for every incoming request.

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

Route-Level Middleware

Route-level middleware executes only for specific routes.

const auth = (req, res, next) => {
  console.log('Authenticated');
  next();
};

app.get('/dashboard', auth, (req, res) => {
  res.send('Dashboard');
});
javascript

Built-in Middleware

Express provides built-in middleware functions for handling common tasks.

app.use(express.json());
javascript

The express.json middleware parses incoming JSON request bodies.

Serving Static Files

Middleware can also serve static assets such as images, CSS files, and JavaScript files.

app.use(express.static('public'));
javascript

Third-Party Middleware

Third-party middleware packages extend Express functionality.

npm install morgan
bash
const morgan = require('morgan');
app.use(morgan('dev'));
javascript

Morgan is commonly used for logging HTTP requests.

Custom Middleware

Developers can create custom middleware for specific business logic.

const logger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
};
javascript

Middleware Execution Order

Middleware executes in the order it is defined in the application.

Improper ordering may cause unexpected application behavior.

Error-Handling Middleware

Error-handling middleware manages application errors centrally.

app.use((err, req, res, next) => {
  res.status(500).json({ error: 'Server Error' });
});
javascript

Authentication Middleware

Authentication middleware protects routes from unauthorized access.

const auth = (req, res, next) => {
  const token = req.headers.authorization;

  if (!token) {
    return res.status(401).send('Unauthorized');
  }

  next();
};
javascript

Using Multiple Middleware Functions

Multiple middleware functions can be applied to a single route.

app.get('/profile', auth, logger, (req, res) => {
  res.send('Profile Page');
});
javascript

Common Beginner Mistakes

Beginners often forget to call the next function, causing requests to hang indefinitely.

Another common mistake is placing middleware in the wrong execution order.

Best Practices

Keep middleware functions focused on a single responsibility.

Use separate files for middleware to maintain a clean project structure.

Real-World Importance

Middleware is essential in production-level applications for security, validation, logging, and request handling.

Most Express.js applications heavily depend on middleware architecture for scalability and maintainability.

Summary

Middleware allows developers to process requests and responses efficiently in Express.js applications.

Understanding middleware is crucial for building scalable and professional backend APIs using Express.js.