Concept Explanation
Imagine a VIP club.
- Security Guard 1: Checks if you are wearing shoes (Logger).
- Security Guard 2: Checks if you have a ticket (Auth).
- The Nightclub: The final destination (The Route).
In Express, Middleware functions are the guards. They run between the request coming in and the response going out. If a guard fails, they can stop the request immediately.
Syntax or Core Structure
Global Middleware
app.use(express.json()); // Parses incoming JSON automatically
Custom Auth Middleware (JWT)
const protect = (req, res, next) => {
const token = req.headers.authorization;
if (token === "secret-key") {
next(); // Let them through!
} else {
res.status(401).send("Unauthorized");
}
};
app.get('/dashboard', protect, (req, res) => {
res.send("Welcome to the secret area!");
});
Real World Example
Request Logging: Every time someone visits your site, a middleware writes the time, the IP address, and the page they visited into a database. This helps you track down bugs and analyze traffic.
Practice Exercises
- The Time Stamper: Create a middleware that adds a
requestTimeproperty to thereqobject so that every route knows exactly when it was called. - The Logger: Build a middleware that
console.logs the HTTP Method and the URL of every single request. - The Auth Mock: Write an auth middleware that only allows the request to continue if the URL includes a query parameter
admin=true.