Code Reference

Express Middleware

Node.js · Reference cheat sheet

Express Middleware

Node.js · Reference cheat sheet


📋 Overview

Middleware functions run in order on a request. Each can read/modify req/res, end the response, or call next(). Most Express power comes from composing middleware.

🔧 Core concepts

SignatureRole
(req, res, next)Normal middleware
(err, req, res, next)Error middleware (must be 4 params)
app.use(fn)All methods / paths (or mount path)
app.use('/api', fn)Only under /api
Built-inPurpose
express.json()Parse JSON bodies
express.urlencoded()Parse form bodies
express.static(dir)Serve static files
express.Router()Modular mini-app

💡 Examples

Logger middleware:

function logger(req, res, next) {
  console.log(req.method, req.url);
  next();
}
app.use(logger);

Auth gate:

function requireAuth(req, res, next) {
  if (!req.headers.authorization) {
    return res.status(401).json({ error: "Unauthorized" });
  }
  next();
}
app.get("/private", requireAuth, (req, res) => res.send("ok"));

Error middleware (last):

app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status || 500).json({ error: err.message });
});

⚠️ Pitfalls

  • Calling next() after res.send can throw "Cannot set headers after they are sent".
  • Order matters: parsers before handlers; error middleware after routes.
  • Async errors need try/catch + next(err) or a wrapper — Express 4 does not catch rejected promises by default (Express 5 improves this).

On this page