Middleware is one of the most powerful features of Express.js. Every request that enters an Express application passes through one or more middleware functions before reaching the final route handler. Understanding middleware is essential for building secure, scalable, and maintainable Node.js applications.
If you're new to Express.js, read our Express.js Tutorial for Beginners: Build Your First Web Server before continuing with this guide.
What Is Middleware?
Middleware is simply a function that executes between receiving an HTTP request and sending an HTTP response.
Middleware has access to:
- Request Object (req)
- Response Object (res)
- Next Middleware Function (next)
Request Flow
Client Request
↓
Middleware 1
↓
Middleware 2
↓
Middleware 3
↓
Route Handler
↓
Response
Your First Middleware
app.use((req, res, next) => {
console.log('Request received');
next();
});
The next() function tells Express to continue processing the request.
next(), the request will stop and never reach your route.
Application-Level Middleware
Application middleware runs for every request.
app.use((req, res, next) => {
console.log(req.method);
next();
});
This middleware logs every HTTP request.
Route-Level Middleware
Middleware can be applied to specific routes.
function auth(req, res, next){
console.log('User Authenticated');
next();
}
app.get('/dashboard', auth, (req, res)=>{
res.send('Dashboard');
});
Here, authentication runs only for the dashboard route.
Built-in Middleware
JSON Parser
app.use(express.json());
Parses incoming JSON requests.
URL Encoded Parser
app.use(express.urlencoded({
extended:true
}));
Parses HTML form data.
Static Files
app.use(express.static('public'));
Serves images, CSS, JavaScript, and other static assets.
Third-Party Middleware
Express has a large ecosystem of middleware packages.
| Package | Purpose |
|---|---|
| cors | Cross-Origin Requests |
| helmet | Security Headers |
| morgan | HTTP Logging |
| compression | Response Compression |
| cookie-parser | Cookie Parsing |
Installing Third-Party Middleware
npm install cors
const cors = require('cors');
app.use(cors());
Creating Custom Middleware
function logger(req,res,next){
console.log(`${req.method} ${req.url}`);
next();
}
app.use(logger);
Custom middleware lets you reuse logic throughout your application.
Authentication Middleware
function authenticate(req,res,next){
if(req.headers.authorization){
next();
}else{
res.status(401).send('Unauthorized');
}
}
This middleware protects private routes.
Error Handling Middleware
app.use((err,req,res,next)=>{
console.error(err);
res.status(500).json({
error:err.message
});
});
Middleware Execution Order
Middleware A
↓
Middleware B
↓
Middleware C
↓
Route
↓
Error Middleware
Express executes middleware in the exact order you register it.
Common Middleware Mistakes
Best Practices
- Keep middleware focused on one responsibility.
- Place middleware in the correct order.
- Always call next() unless sending a response.
- Use Helmet for security.
- Use Morgan for logging.
- Validate incoming requests.
- Handle errors centrally.
Conclusion
Middleware is one of the core building blocks of Express.js. Once you understand how middleware works, you'll be able to create cleaner, more secure, and more maintainable applications.
Whether you're building a REST API, HRMS, ERP, e-commerce platform, or enterprise application, middleware helps organize your application logic while improving security and performance.
About ShasTech-IT
ShasTech-IT builds scalable Node.js applications, REST APIs, ERP systems, HRMS platforms, WMS software, Android applications, and custom business solutions for organizations worldwide.