What is middleware in Express and how does it work?
Quick answer
Middleware are functions that receive the request, response and a next callback; they run in the order they are registered and can modify the request, end the response or pass control on with next().
Each middleware can do work such as logging, parsing JSON bodies, checking authentication or setting headers, and then either sends a response or calls next() to continue to the next function. Order matters: a body parser must be registered before the routes that read req.body.
Error-handling middleware has four parameters (err, req, res, next) and is registered last. In Express 4, an error thrown inside an async handler is not caught automatically; you must catch it and call next(err) or use a small wrapper (Express 5 handles rejected promises for you).
app.use(express.json());
function requireAuth(req, res, next) {
if (!req.headers.authorization) return res.status(401).json({ error: "Unauthorized" });
next();
}
app.get("/profile", requireAuth, (req, res) => res.json({ ok: true }));
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: "Something went wrong" });
});