Middleware is simply a function in Express that runs between the incoming request and the final response. It works like a checkpoint before the actual response is sent.
π§ What is Middleware?
Middleware is a function that can check, modify, verify, or process the incoming request before it reaches the final handler. It sits in the middle of the request and the response.
Real Life Example:
When you enter a mall, security checks your bag before letting you inside.
That security check is Middleware.
// Middleware structure
app.use((req, res, next) => {
console.log("Middleware working...");
next(); // Moves to next middleware or route
});
π How to Use Middleware?
We use app.use() to apply middleware:
app.use((req, res, next) => {
console.log("Request received at:", new Date());
next();
});
π When to Use Middleware?
When you want to check user authentication
When you want to log request details (time, method, route)
express.json() is a built-in middleware that helps Express read JSON data from the client and make it available as req.body.
app.use(express.json()); // enables JSON body reading
app.post("/save", (req, res) => {
console.log(req.body);
res.send("Data Received Successfully");
});
Simple Explanation:
When someone sends data (a parcel), itβs packed in a box.
express.json() opens that box and gives us the contents in readable form.
β Final Summary
Middleware = Function between Request & Response
app.use() = Apply middleware to all requests
Used for authentication, validation, logging, parsing
express.json() = Reads request JSON data and puts it into req.body