Express Middleware - Easy Explanation

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?

🎯 Why Should We Use Middleware?

πŸ§ͺ Example With a Route

app.use((req, res, next) => {
  console.log("Middleware executed");
  next(); // continue processing
});

app.get("/", (req, res) => {
  res.send("Home Page Loaded");
});
    

🍫 Special Middleware: express.json()

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