Middleware
Last Updated : Oct 2026
Middleware is a function that runs between the request and the response. It allows you to modify the request and response objects before they reach the route handler.
Middleware functions are executed in the order they are added to the router, from top to bottom.
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware in the stack.
next middleware is used to pass control to the next middleware in the stack.
There are three types of middleware:
- Custom Middleware: Created by you.
- Built-in Middleware: Provided by Express.
- Third-party Middleware: Middleware created by other developers.
Custom Middleware
Syntax:
app.use(function (req, res, next) {
// code to be executed for each request
next(); // call the next middleware
});
Example:
import express from "express";
const app = express();
app.use(function (req, res, next) {
req.data = "Data from middleware"; //Also passing data to the next middleware
console.log("Middleware executed!");
next(); // call the next middleware
});
app.get("/", function (req, res) {
console.log(req.data); // Output: "Data from middleware"
res.send("Hello, World!");
});
app.listen(3000, function () {
console.log("Server started on http://localhost:3000");
});
In each request, the middleware will be executed in the order they are added to the router.
Specific Middleware
You can also add middleware to specific routes.
const checkAuth = (req, res, next) => {
console.log("Checking authentication...");
next();
};
const logger = (req, res, next) => {
console.log("Request received");
next();
};
app.get("/profile", checkAuth, (req, res) => {
res.send("Profile");
});
// Multiple Middleware
app.get("/dashboard", logger, checkAuth, (req, res) => {
res.send("Dashboard");
});
Execution order:
Request
↓
logger
↓
checkAuth
↓
Route handler
↓
Response
Built-in Middleware
Some of the built-in middleware provided by Express are:
express.static()
The express.static() middleware is used to serve static files from a specified directory. This middleware will serve files from the "public" directory when a request is made to the root URL ("/").
app.use(express.static("public"));
Such as images,html, stylesheets, and JavaScript files.
http://localhost:3000/index.html
express.urlencoded()
The express.urlencoded() middleware is used to parse URL-encoded data from the request body. This middleware will parse the request body and make it available in the req.body object.
Example:
app.use(express.urlencoded({ extended: true }));
app.post("/login", (req, res) => {
console.log(req.body);
res.send("Login received");
});
<form method="POST" action="/login">
<input name="username" />
<input name="password" />
<button>Login</button>
</form>
express.json()
The express.json() middleware is used to parse JSON data from the request body. This middleware will parse the request body and make it available in the req.body object.
Example:
app.use(express.json());
app.post("/users", (req, res) => {
console.log(req.body);
if (!req.body) return res.status(400).json({ message: "No data received" });
res.json({
message: "User received",
data: req.body,
});
});
Error-handling middleware
Express provides a built-in middleware for handling errors. This middleware is used to handle errors that occur during the request-response cycle.
Note: Make sure the error middleware comes after your routes
app.use((err, req, res, next) => {
console.error(err);
res.status(err.status || 500).json({
success: false,
message: err.message,
});
});
Notice the four arguments:
"This is an error-handling middleware."
- err: The error object.
- req: The request object.
- res: The response object.
- next: The next middleware function in the stack.
if an error occurs, it will be passed to the error-handling middleware.
app.get("/test", async (req, res) => {
throw new Error("Database failed");
});
Third-party Middleware
Third-party middleware is middleware created by other developers.So we can install them using npm.
npm install package-name
cors()
The cors() middleware is used to enable CORS (Cross-Origin Resource Sharing) for the Express application.
npm install cors
import cors from "cors";
const app = express();
// All origins
app.use(cors());
// Specific origins
app.use(
cors({
origin: "http://localhost:3000",
}),
);
Now a frontend running on another origin can make requests to your API, subject to the CORS configuration.
helmet()
The helmet() middleware is used to help secure your Express application by setting various HTTP headers.
npm install helmet
import helmet from "helmet";
const app = express();
app.use(helmet());
morgan()
The morgan() middleware is used to log HTTP requests in the console.Very useful during development.
npm install morgan
import morgan from "morgan";
const app = express();
app.use(morgan("dev"));
GET /users 200 5.123 ms - 245
cookie-parser()
The cookie-parser() middleware is used to parse cookies in the request.
npm install cookie-parser
import cookieParser from "cookie-parser";
const app = express();
app.use(cookieParser());
app.get("/", (req, res) => {
console.log(req.cookies);
});
{ cookieName: 'cookieValue' }
Note: res.cookie() is provided by Express, while req.cookies parsing is what cookie-parser traditionally provides.
