NelsonLabs
Express.js/Middleware

Middleware

Middleware is the most powerful concept in Express. Every request flows through a pipeline of middleware functions before reaching the route handler. This is how logging, authentication, body parsing, and CORS work.

ANALOGY

An airport security line. Every passenger (request) goes through the same checkpoints: ticket check, ID check, security scan, gate boarding. Each checkpoint can stop a passenger (reject the request) or wave them through to the next checkpoint. Express middleware is that security line โ€” every request flows through, and each middleware decides to pass it on or respond.

Middleware anatomy and usage
javascript
// A middleware function receives (req, res, next)
// Call next() to pass control to the next middleware
// Call res.send/json() to end the request

function logger(req, res, next) {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();  // pass to next middleware
}

// Apply globally โ€” runs for EVERY request
app.use(logger);

// Apply to specific path โ€” runs for any method on /api/*
app.use("/api", authenticate);

// Apply to specific route
app.get("/admin", isAdmin, adminHandler);

// Multiple middleware on a single route
app.post("/courses", authenticate, validate, rateLimiter, createCourse);
Built-in and third-party middleware
javascript
// Built-in Express middleware
app.use(express.json());              // parse JSON bodies
app.use(express.urlencoded({ extended: true })); // parse form data
app.use(express.static("public"));   // serve static files

// npm install cors
const cors = require("cors");
app.use(cors({
  origin: ["http://localhost:3000", "https://nelsonlabs.dev"],
}));

// npm install morgan
const morgan = require("morgan");
app.use(morgan("dev"));  // HTTP request logging
// dev: "GET /api/courses 200 4.321 ms - 1024"