Middleware in Express.js is a function that has access to the request (req) and response (res) objects, and the next function (next) in the request-response cycle.
- Middleware can execute code, modify req/res, end the request, or pass control to the next middleware.
- Middleware is used for logging, authentication, parsing request bodies, error handling, etc.
🔹 Middleware Signature
function middleware(req, res, next) {
// Do something
next(); // Pass to next middleware/route
}
🔹 Types of Middleware
- Application-level middleware – applied to all routes or specific routes.
- Router-level middleware – applied to routes using an Express router.
- Built-in middleware – like
express.json(),express.static(). - Error-handling middleware – handles errors with 4 parameters
(err, req, res, next).
🔹 Example 1: Application-level Middleware
const express = require("express");
const app = express();
const PORT = 3000;
// Built-in middleware to parse JSON
app.use(express.json());
// Custom middleware for logging
app.use((req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
next();
});
app.get("/hello", (req, res) => {
res.send("Hello World");
});
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Output when accessing /hello:
GET /hello - 2025-10-22T10:00:00.000Z
🔹 Example 2: Route-specific Middleware
function authMiddleware(req, res, next) {
const token = req.headers["authorization"];
if (token === "12345") next();
else res.status(401).json({ message: "Unauthorized" });
}
app.get("/protected", authMiddleware, (req, res) => {
res.send("This is protected content");
});
🔹 Example 3: Error-handling Middleware
app.get("/error", (req, res) => {
throw new Error("Something went wrong!");
});
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: err.message });
});
✅ Key Points
- Middleware is executed in order they are added.
- Must call
next()to pass control unless you end the response. - Common use cases: logging, authentication, request parsing, error handling, compression, CORS.