What is Middleware?
Middleware functions are functions that have access to the request (req
), response (res
), and the next middleware function in the application’s request-response cycle. Middleware can:
- Execute any code.
- Modify the
req
andres
objects. - End the request-response cycle.
- Call the next middleware function in the stack.
Middleware is executed in the order it is defined in the Express application.
Why Use Middleware?
Middleware provides a structured way to handle common tasks such as:
- Logging: Record details about incoming requests.
- Authentication: Verify users’ credentials.
- Error Handling: Catch and respond to errors gracefully.
- Static File Serving: Serve files like images, CSS, and JavaScript.
- Data Parsing: Parse incoming request bodies (e.g., JSON or form data).
Types of Middleware
Built-in Middleware
Express provides some built-in middleware for common tasks:
- express.json(): Parses incoming requests with JSON payloads.
- express.urlencoded(): Parses URL-encoded payloads.
- express.static(): Serves static files.
Third-party Middleware
Some popular third-party middleware includes:
- morgan: HTTP request logger.
- cors: Enable Cross-Origin Resource Sharing.
- helmet: Secure your app by setting various HTTP headers.
Custom Middleware
You can create custom middleware to handle application-specific logic.
How Middleware Works
Middleware functions are defined using the following syntax:
app.use((req, res, next) => {
console.log('Middleware executed');
next(); // Pass control to the next middleware
});
The next
function is critical for moving to the next middleware. If next
is not called, the request will hang.
Example: Middleware in Action
Here’s an example demonstrating built-in, third-party, and custom middleware:
const express = require('express');
const morgan = require('morgan');
const app = express();
// Built-in middleware
app.use(express.json());
// Third-party middleware
app.use(morgan('dev'));
// Custom middleware
app.use((req, res, next) => {
console.log(`Request received: ${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Best Practices for Middleware
- Keep Middleware Modular: Separate middleware logic into different files or modules.
- Order Matters: Place middleware in the correct sequence for the desired functionality.
- Error Handling: Always include error-handling middleware as the last middleware.
- Leverage Third-party Middleware: Use well-maintained libraries for common tasks.
- Avoid Overloading Middleware: Keep middleware focused on a single responsibility.
Understanding middleware is fundamental to mastering Express.js. By leveraging middleware effectively, you can create robust and efficient web applications.
About Lavesh Katariya
Innovative Full-Stack Developer | Technical Team Lead | Cloud Solutions Architect
With over a decade of experience in building and leading cutting-edge web application projects, I specialize in developing scalable, high-performance platforms that drive business growth. My expertise spans both front-end and back-end development, making me a versatile and hands-on leader capable of delivering end-to-end solutions.