Custom Middleware
The Border Crossing
Section titled “The Border Crossing”We know that middleware sits in the middle. But how do we write our own?
Think of your custom middleware as a Border Control Station. Every request must pass through it to enter the country (your route handlers).
Fig 1: Papers, please.
The Three Outcomes
Section titled “The Three Outcomes”When a vehicle (request) pulls up to the booth, the officer (middleware) has three choices:
- Welcome (Success): “You’ve arrived.” Middleware can send a response immediately if it wants to (e.g., a cache hit or health check).
res.status(200).send("Welcome")
- Access Denied (Failure): “Your passport is expired. Turn around.”
res.status(403).send("Access Denied")
- Inspect & Pass (Next): “Open your trunk. Okay, looks good.” The officer attaches a “Checked” sticker and waves you through.
req.checked = true; next()
Code: The Officer
Section titled “Code: The Officer”const authOfficer = (req, res, next) => { // 1. Immediate Success (The Fifth Element) // Using query params for easy browser testing: ?passport=multi-pass if (req.query.passport === 'multi-pass') { return res.status(200).send('Welcome, Leeloo Dallas.'); }
// 2. Access Denied if (req.query.passport === 'banned') { return res.status(403).send('Access Denied. Turn around.'); }
// 3. Inspect (Look in the trunk) console.log('Looking in the trunk...'); req.customsCheckRequired = true; // Attach the sticker next(); // wave them to inspections};
app.use(authOfficer);Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Express Middleware - Demo Repo
Express: Writing Middleware