You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Middleware is one of the most powerful and central concepts in Express. Understanding it unlocks logging, authentication, body parsing, error handling, and much more.
A middleware function is a function with access to the req (request) object, the res (response) object, and next — a function that passes control to the next middleware in the chain.
function myMiddleware(req, res, next) {
console.log("Request received:", req.method, req.url);
next(); // pass control to the next handler
}
If you do not call next(), the request hangs and the client never receives a response.
Use app.use() to apply middleware globally (to all routes):
const express = require("express");
const app = express();
// Runs for every request
app.use(function (req, res, next) {
console.log(new Date().toISOString(), req.method, req.url);
next();
});
app.get("/", function (req, res) {
res.send("Home");
});
app.listen(3000);
Express ships with useful built-in middleware:
app.use(express.json()); // parse JSON bodies
app.use(express.urlencoded({ extended: true })); // parse form bodies
app.use(express.static("public")); // serve static files
Popular npm packages integrate as Express middleware:
npm install morgan cors helmet
const morgan = require("morgan");
const cors = require("cors");
const helmet = require("helmet");
app.use(helmet()); // sets security-related HTTP headers
app.use(cors()); // enables Cross-Origin Resource Sharing
app.use(morgan("dev")); // logs requests in colour-coded format
Apply middleware to specific routes or routers only:
function requireAuth(req, res, next) {
const token = req.headers["authorization"];
if (!token) {
return res.status(401).json({ error: "Unauthorized" });
}
next();
}
app.get("/admin", requireAuth, function (req, res) {
res.json({ secret: "admin data" });
});
An error-handling middleware function takes four parameters. Express identifies it by the extra argument and routes errors to it when you call next(err):
// At the end of your middleware stack
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).json({ error: "Internal Server Error" });
});
Trigger it by passing an error to next():
app.get("/broken", function (req, res, next) {
const error = new Error("Something went wrong");
next(error);
});
Middleware is the mechanism that keeps Express applications composable. Rather than building monolithic handlers, you chain small, focused functions — each doing one thing well — and Express wires them together in the order you define them.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.