Middleware is a function that runs between a request and a response π§
In simple words
Middleware acts like a checkpoint
That processes requests before they reach the main logic π¦
Without middleware β
β’ No authentication checks
β’ No request validation
β’ No centralized logic
π§ What Middleware Is Used For
β’ Authentication and authorization π
β’ Logging requests π
β’ Validating data β
β’ Handling errors β οΈ
β’ Parsing request body π¦
π Real World Examples
β’ Checking if user is logged in
β’ Verifying JWT tokens
β’ Logging API requests
β’ Blocking unauthorized access
π How Middleware Works
Client sends request π€
Middleware processes request π
Request reaches route handler π£οΈ
Response goes back to client π©
π» Example: Middleware in Express
function authMiddleware(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send("Unauthorized");
}
next();
}
app.use(authMiddleware);
app.get("/dashboard", (req, res) => {
res.send("Welcome to dashboard");
});