Middleware functions run during the request-response cycle, sitting between the incoming
request and the final route handler. They can read or change req/res, end the cycle by
sending a response, or hand off control with next().
Syntax
app.use((req, res, next) => {
console.log("Middleware executed");
next();
});
How middleware executes
- A request reaches the server.
- Middleware functions run in the order they were registered.
- Each one either sends a response or calls
next(). - If nothing ends the cycle, the matching route handler runs and sends the final response.
Types of middleware
1. Application-level — runs for the whole app.
app.use(express.json());
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
2. Router-level — scoped to one router instance.
const router = express.Router();
router.use((req, res, next) => {
console.log("Router-specific middleware");
next();
});
router.get("/dashboard", (req, res) => {
res.send("Dashboard Page");
});
app.use("/account", router);
3. Error-handling — takes four arguments, defined after routes.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Something went wrong!");
});
4. Built-in — ships with Express.
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
5. Third-party — installed from npm.
const morgan = require("morgan");
app.use(morgan("dev"));
Putting it together
const express = require("express");
const app = express();
const port = process.env.PORT || 5100;
app.use((req, res, next) => {
console.log(`Request received: ${req.method} ${req.url}`);
next();
});
app.get("/", (req, res) => {
res.send("<h2>Bookstore API</h2><p>Middleware tutorial</p>");
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Visiting / logs the request in the terminal and shows the HTML page in the browser.