Middleware is software that sits in the middle of a processing pipeline. In web frameworks it usually means functions that run on each request before the final handler, and on the response afterward, handling shared concerns such as logging, authentication or compression.
Why it matters
Middleware keeps cross-cutting logic out of individual routes. Instead of repeating a login check in fifty handlers, one middleware does it once and either passes the request along or stops it with an error. Order matters because each step can change what the next step sees. Express, Django, ASP.NET and Laravel all use the pattern. The word is also used more broadly for software connecting separate systems, such as message brokers.
Example
app.use((req, res, next) => {
console.log(req.method, req.url);
next(); // pass to the next step
});
app.use((req, res, next) => {
if (!req.headers.authorization) return res.status(401).end();
next();
});
Common mistakes
- Forgetting to call
next()or send a response, so requests hang. - Putting middleware in the wrong order, such as authentication after the route it should protect.
- Doing slow work in middleware that runs on every request.
Related
Get notified when this term updates
Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.
This page is general information written by our editorial team and updated when documentation changes. Servers and providers differ, so test changes safely first. See our editorial policy and disclaimer.