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();
};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();
});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');
});Built-in Middleware
Express provides built-in middleware functions for handling common tasks.
app.use(express.json());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'));Third-Party Middleware
Third-party middleware packages extend Express functionality.
npm install morganconst morgan = require('morgan');
app.use(morgan('dev'));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();
};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' });
});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();
};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');
});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.