Middleware are function that runs between request from the client and response from the server.
Each middleware function has access to :
- req - request object
- res- response object
- next() - a function that pass control to next middleware.
Signature of middleware function
function middlewareName(req, res, next) {
// Do something
next(); // move to next middleware
}
if forgot to call next(), the request-response cycle will hang.
Express has 5 types of middleware:
- Application-level
- Router-level
- Built-in
- Third-party
- Error-handling
Application-level middleware
- Bound to an app object using app.use() or app.METHOD().
- Runs for every request or specific routes.
app.use((req, res, next) => {
console.log("Application middleware executed");
next();
});
Router-level Middleware
- Works the same as application-level, but bound to an express.Router() instance.
- Useful for modular route handling.
const router = express.Router();
router.use((req, res, next) => {
console.log("Router middleware executed");
next();
});
app.use("/api", router);
Built-in Middleware
Comes with Express by default.
Common ones are:
- express.json() → parse JSON body
- express.urlencoded() → parse form data
- express.static() → serve static files
app.use(express.json());
app.use(express.static("public"));
Third-party Middleware
Installed via npm to add extra features.
Examples:
- morgan → request logging
- cookie-parser → parse cookies
- cors → handle cross-origin requests
- helmet → security headers
const morgan = require("morgan");
app.use(morgan("dev"));
Error-handling Middleware
- Special middleware with 4 parameters: (err, req, res, next).
- Used to handle errors globally.
app.use((err, req, res, next) => {
console.error(err.message);
res.status(500).send("Something broke!");
});
Top comments (0)