Middleware in Express
Middleware in Express
Middleware are functions that run in order between a request arriving and the final response. They can transform the request, short-circuit it, or run side effects.
What middleware looks like
A middleware function receives request, response, and a next callback:
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
Calling next hands control to the next middleware or route in the chain. Skipping it leaves the request hanging.
Built-in middleware
express.json parses JSON bodies, and express.urlencoded parses form data. cors and helmet are popular third-party additions:
app.use(express.json());
Route-level middleware
You can attach middleware to a single route:
app.get('/admin', isAuthed, (req, res) => { ... });
isAuthed runs before the handler. If the check fails it sends an error and never calls next, protecting the route.
Order matters
Middleware run in registration order. A logger must be registered before routes for it to see every request. Error middleware, which takes four arguments, is registered last and catches errors thrown by earlier handlers.
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ message: 'Server error' });
});
Key Points
- Middleware chain request handling before the route.
- next passes control onward; skipping it stalls.
- Third-party middleware add parsing, CORS, and security.
- Route-level middleware guard specific endpoints.
- The four-argument form catches errors globally.