Middleware
Middleware are functions that run in order on every request before your route, able to change request and response.
In this page:
Syntax
app.use((req, res, next) => {
// modify req or res
next();
});
Middleware
A middleware has the signature (req, res, next). It can modify req or res, end the response, or call next to pass control on.
Register with app.use. Built-in ones include express.json and express.static, and third-party ones cover logging, CORS and auth.
Note:
Forgetting next() makes requests hang.
Example: Middleware
const express = require("express");
const app = express();
app.use((req, res, next) => {
req.startedAt = Date.now();
console.log(req.method, req.url);
next();
});
app.use(express.json());
app.get("/", (req, res) => res.send("ok in " + (Date.now() - req.startedAt) + "ms"));
app.listen(3000);
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting to call next
- Registering middleware after routes
- Calling next after sending a response
Chapter Summary
- Signature is (req, res, next)
- app.use registers it
- next passes control
- Order matters
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: