🔍 What is Middleware?
In Node.js, especially when using Express.js, middleware is like a middle layer that sits between the incoming request (from the client) and the final response (from the server).
- Middleware functions are like checkpoints that process requests step by step.
- Each middleware can read, change, or stop the request before it reaches the final handler.
- Middleware can also modify the response before sending it back to the client.
🛠️ Types of Middleware in Express.js
There are different types of middleware in Express.js. Let’s break them down one by one:
1. Application-level Middleware
- These are applied directly to your Express app.
- They run for every request unless limited to specific routes.
- Example: Logging requests, parsing JSON, checking authentication.
2. Router-level Middleware
- These middleware functions are applied to specific routes.
- They only run when those routes are accessed.
- Example: Adding authentication for only /admin routes.
3. Built-in Middleware
- These come pre-built in Express.js.
- You don’t need to install them separately.
- Example: express.json() for parsing JSON request bodies.
4. Error-handling Middleware
- Special middleware created to catch and handle errors.
- This ensures that your app does not crash when something goes wrong.
- Example: Sending a user-friendly error message when the server encounters a problem.
💻 Example of Middleware
Example of middleware in an Express.js app:
// Express.js middleware
const express = require('express');
const app = express();
// Application-level middleware (logs every request)
app.use((req, res, next) => {
console.log(`Request Method: ${req.method}, URL: ${req.url}`);
next(); // Passes the request to the next middleware/route
});
// Built-in middleware (parsing JSON)
app.use(express.json());
// Router-level middleware for a specific route
app.get('/hello', (req, res) => {
res.send('Hello World!');
});
// Error-handling middleware
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');
});
Explanation of this example:
- The first middleware logs every incoming request (method + URL).
- The second middleware parses JSON request bodies.
- The /hello route returns a simple response.
- The error-handling middleware catches unexpected errors and returns a response instead of crashing the app.
📊 Key Benefits of Middleware
- Reusability: You can reuse middleware functions across different projects.
- Modularity: Keeps code clean by separating different functionalities.
- Flexibility: Apply middleware only where it’s needed.
- Error Handling: Helps catch and manage errors in one place.
📝 Summary
In Express.js, middleware is like a chain of steps that handle requests and responses. Each middleware can log data, parse requests, authenticate users, or handle errors. Using middleware makes your Node.js applications cleaner, reusable, modular, and easier to maintain. That’s why middleware is one of the most important concepts in Express.js.