Skip to content

Chaining Middleware

We don’t just have to rely on app.use() (global middleware). We can line up multiple middleware functions for a specific route.

Think of it as a series of laser gates. You have to pass every single one to get to the destination.

A long sci-fi tunnel with multiple glowing scanner rings spaced out sequentially.

Fig 1: Sequential Processing. One path, multiple rings.

app.get(
'/vip-lounge',
logger, // 1. Ring 1: Log the attempt
authCheck, // 2. Ring 2: Check the ID
suitCheck, // 3. Ring 3: Check the dress code
(req, res) => {
// 4. Destination Reached
res.send('Welcome to the Platinum Club.');
}
);

Express runs these functions in strict order (left to right, top to bottom).

Crucial Logic: If any middleware sends a response (e.g., res.status(403).send(...)), the chain stops immediately. The subsequent functions never run. The request is “ejected” from the gauntlet.

Think of middleware like Standardized Security Equipment.

You have a “Metal Detector” (middleware). You can install that same machine at the Stadium Entrance, the Airport Gate, and the Court House.

  • You write the logic once.
  • You apply it to many different routes.

You don’t build a custom metal detector for every door. You just move the equipment where you need it.


Express Middleware Chaining - Demo Repo

Express API: App Methods

⏭ Surveillance

Writing loggers is boring. Let’s install a camera.