🌟 Week 7 — Day 4: Middleware
Good morning campers! 👋🔥
Today we step into one of the MOST IMPORTANT concepts in Express: middleware.
If Express was a restaurant, middleware is EVERYTHING that happens between a customer entering the door and receiving their food.
🧱 1. What is Middleware?
✔ Middleware = “In-Between Processing”
In Express, middleware is:
A function that sits between the request and the response. It can examine, modify, stop, or continue the flow.🔍 The Formula:
(req, res, next) => { ... }
req → incoming request
res → outgoing response
next() → lets the request move to the next middleware or route
🍔 Restaurant Analogy
Imagine Express as a restaurant:
➤Customer enters → This is the ➤incoming request (req)
➤Security checks bag → Middleware
➤Waiter takes order → Middleware
➤Kitchen cooks food → Route handler
➤Waiter serves food → Response (res)
Each “step” is middleware.
Some steps check things, others prepare things, others add data, some reject requests.
🧠 2. Why Do We Need Middleware?
Middleware helps you:
➙Check if the user is logged in ✔
➙Parse JSON sent from frontend ✔
➙Log incoming requests ✔
➙Serve static files ✔
➙Handle errors ✔
➙Validate data ✔
➙Limit access (rate limiting) ✔
➙Clean or modify requests ✔
Without middleware, Express is basically a blank application that does… nothing.
⚙️ 3. Built-In Middleware in Express
Express gives you ready-made middleware out of the box.
💡 3.1 express.json()
This middleware reads JSON sent in the request body and makes it available at req.body.
➤Without express.json()
You can’t read JSON!
➤With express.json()
app.use(express.json());
Now when you do:
POST /login { "username": "megersa", "password": "1234" }
You can access it:
req.body.username
req.body.password
🎯 Analogy
This is like having a translator in a restaurant who takes what the customer says and converts it into your language.
💡 3.2 express.static()
Allows you to serve static files (images, CSS, HTML, JS).
app.use(express.static("public"));
This means:
➣/public/index.html → available at http://localhost:3000/index.html
➣/public/style.css → served automatically
🎯 Analogy:
Think of this as the restaurant’s self-service shelf.
Customers help themselves to menus, napkins, water… without the waiter.
🖌️ 4. Custom Middleware
You can make your own middleware functions.
Basic template:
function myMiddleware(req, res, next) {
console.log("Middleware ran!");
next();
}
app.use(myMiddleware);
Steps:
➙It runs on EVERY request
➙It prints something
➙It calls next() to let the request continue
🎯 Analogy
Custom middleware = a custom security guard or waiter procedure that you invent for your restaurant.
🧪 5. Real Examples of Custom Middleware
Example 1 — Logging Middleware
What it does: ➤Logs the method (GET, POST) ➤Logs the path ➤Allows request to continue Example 2 — Add Timestampapp.use((req, res, next) => { console.log(${req.method} ${req.url}); next(); });
app.use((req, res, next) => {
req.requestTime = new Date().toISOString(); next(); });
Later in a route:
app.get("/", (req, res) => {
res.send("Requested at: " + req.requestTime); });
🎉 Middleware can add new data to req!
Example 3 — Restrict Access (Simple Auth Check)
app.use((req, res, next) => {
const token = req.headers["authorization"];
if (!token){ return res.status(403).send("Access denied");}
next(); });
Middleware can ALLOW or BLOCK requests.21 Nov 2025, 01:11
