Skip to content

Custom Middleware

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).

Cyberpunk international border crossing with a holographic customs officer. One lane green for ENTER, one lane red for DENIED.

Fig 1: Papers, please.

When a vehicle (request) pulls up to the booth, the officer (middleware) has three choices:

  1. 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")
  2. Access Denied (Failure): “Your passport is expired. Turn around.”
    • res.status(403).send("Access Denied")
  3. Inspect & Pass (Next): “Open your trunk. Okay, looks good.” The officer attaches a “Checked” sticker and waves you through.
    • req.checked = true; next()
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);

Express Middleware - Demo Repo

Express: Writing Middleware

⏭ The Gauntlet

One checkpoint is fine. But what if we need a whole security team?