If you have started learning Express.js, you have probably seen code like this:
app.use(express.json());
You may have also seen:
app.use((req, res, next) => {
console.log("Request received");
next();
});
At first, middleware can feel a little confusing.
What exactly is middleware?
Why do we need next()?
Why do we use app.use()?
And what are all these different types of middleware?
Middleware is actually one of the most important concepts in Express.js. Once you understand it, things like authentication, logging, validation, error handling, file uploads, and request processing become much easier to understand.
In this article, we'll learn:
- What middleware means
- How middleware works
- What
req,res, andnextmean - How
app.use()works - Different types of Express.js middleware
- Application-level middleware
- Router-level middleware
- Built-in middleware
- Third-party middleware
- Error-handling middleware
- Custom middleware
- Authentication middleware
- Validation middleware
- Middleware execution order
- Common middleware mistakes
- A practical middleware example
Let's start with the basics.
What Is Middleware in Express.js?
Middleware is a function that runs between the incoming request and the final response.
A simple Express route looks like this:
app.get("/users", (req, res) => {
res.json({
message: "Users fetched successfully"
});
});
With middleware, the flow becomes:
Client
↓
Request
↓
Middleware
↓
Route Handler
↓
Response
↓
Client
Middleware can inspect or modify the request, perform some operation, and then decide whether the request should continue.
For example:
app.use((req, res, next) => {
console.log("Request received");
next();
});
The middleware runs first.
Then next() tells Express:
"I'm done. Continue to the next middleware or route."
The Basic Middleware Structure
A middleware function normally looks like this:
(req, res, next) => {
// Middleware logic
next();
}
There are three important parameters:
req
↓
Request object
res
↓
Response object
next
↓
Move to the next middleware
Let's understand them.
The req object contains information about the incoming request.
The res object is used to send a response back to the client.
next() — Continue the Request
next() is one of the most important concepts in Express middleware.
Consider:
app.use((req, res, next) => {
console.log("Middleware 1");
next();
});
app.get("/", (req, res) => {
res.send("Home page");
});
The flow is:
Request
↓
Middleware 1
↓
next()
↓
Route handler
↓
Response
Without:
next();
the request can stop there if the middleware doesn't send a response.
What Happens If We Don't Call next()?
Consider:
app.use((req, res, next) => {
console.log("Middleware executed");
});
There is no:
next();
and no:
res.send();
The request will remain waiting.
The client may continue showing a loading state because Express doesn't know what to do next.
So a middleware generally needs to do one of two things:
Continue the request
next();
or:
Send a response
res.json(...);
A Simple Middleware Example
Let's create a basic Express application.
npm init -y
npm install express
Create:
server.js
Then:
const express = require("express");
const app = express();
app.use((req, res, next) => {
console.log("Middleware executed");
next();
});
app.get("/", (req, res) => {
res.send("Home page");
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Now open:
http://localhost:3000
You'll see:
Home page
And your terminal will show:
Middleware executed
Why Do We Need Middleware?
Imagine you have 20 API routes:
GET /api/users
POST /api/users
GET /api/products
POST /api/products
GET /api/orders
POST /api/orders
...
Suppose you want to log every request.
Without middleware, you might have to write:
app.get("/api/users", (req, res) => {
console.log(req.method, req.url);
// ...
});
and repeat it for every route.
That's not a good approach.
Instead:
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
Now the middleware can handle logging for every request.
This is one of the main benefits of middleware:
Middleware allows us to reuse common request-processing logic.
Types of Express.js Middleware
Express.js middleware can be broadly divided into several categories:
1. Application-level middleware
2. Router-level middleware
3. Built-in middleware
4. Third-party middleware
5. Error-handling middleware
6. Custom middleware
Let's understand each one.
1. Application-Level Middleware
Application-level middleware is attached directly to the Express application using:
app.use()
or:
app.METHOD()
For example:
app.use((req, res, next) => {
console.log("Application middleware");
next();
});
This middleware runs for requests that match its path.
If no path is provided:
app.use((req, res, next) => {
console.log("Runs for every request");
next();
});
it can run for every incoming request.
Example: Application-Level Logging Middleware
app.use((req, res, next) => {
console.log(
`${req.method} ${req.url}`
);
next();
});
Now requests such as:
GET /api/users
POST /api/users
DELETE /api/users/10
can be logged automatically.
For example:
GET /api/users
POST /api/users
DELETE /api/users/10
This is useful for debugging and monitoring.
Application Middleware with a Specific Path
You can also limit middleware to a specific path.
app.use("/api", (req, res, next) => {
console.log("API middleware");
next();
});
Now:
/api/users
/api/products
/api/orders
will pass through this middleware.
But:
/about
/contact
will not.
This is useful when you want middleware to apply only to a particular group of routes.
2. Router-Level Middleware
Router-level middleware works similarly to application-level middleware, but it is attached to an Express router.
For example:
const express = require("express");
const router = express.Router();
router.use((req, res, next) => {
console.log("Router middleware");
next();
});
router.get("/users", (req, res) => {
res.json({
message: "Users"
});
});
app.use("/api", router);
Now the router handles:
/api/users
The middleware runs before the route handler.
Why Use Router-Level Middleware?
Imagine your application has:
/api/users
/api/products
/api/orders
/api/admin
Maybe you only want certain middleware for admin routes.
You can create:
const adminRouter = express.Router();
adminRouter.use((req, res, next) => {
console.log("Admin middleware");
next();
});
Then:
adminRouter.get("/users", ...);
adminRouter.delete("/users/:id", ...);
app.use("/api/admin", adminRouter);
Now the middleware only applies to:
/api/admin/*
This helps keep larger Express applications organized.
3. Built-in Middleware
Express includes several middleware functions out of the box.
Some commonly used ones are:
express.json()
express.urlencoded()
express.static()
Let's look at them.
express.json()
This middleware parses incoming JSON request bodies.
For example, the client sends:
{
"name": "John",
"email": "john@example.com"
}
Use:
app.use(express.json());
Then you can access:
req.body
Example:
app.use(express.json());
app.post("/api/users", (req, res) => {
console.log(req.body);
res.json({
data: req.body
});
});
Without JSON parsing middleware, req.body may not contain the parsed JSON data.
express.urlencoded()
This middleware parses URL-encoded form data.
For example:
app.use(express.urlencoded({ extended: true }));
It is commonly used when handling traditional HTML form submissions.
Example form data:
name=John&email=john@example.com
Then:
req.body
can contain:
{
name: "John",
email: "john@example.com"
}
express.static()
This middleware is used to serve static files.
For example, suppose you have:
public/
├── index.html
├── styles.css
└── image.png
You can expose the directory using:
app.use(express.static("public"));
Now Express can serve those files directly.
For example:
http://localhost:3000/index.html
can load:
public/index.html
This is useful for serving:
- Images
- CSS
- JavaScript files
- HTML
- Other static assets
4. Third-Party Middleware
Express also has a large ecosystem of third-party middleware.
These are packages that you install separately and use in your application.
Some popular examples include:
cors
helmet
morgan
cookie-parser
multer
express-rate-limit
Let's look at a few.
CORS Middleware
CORS is commonly needed when your frontend and backend run on different origins.
Install:
npm install cors
Then:
const cors = require("cors");
app.use(cors());
Now your Express application can handle cross-origin requests according to the configured CORS policy.
You can also configure specific origins:
app.use(
cors({
origin: "http://localhost:3001"
})
);
This is common when developing a React frontend separately from an Express backend.
Helmet Middleware
Helmet helps set various HTTP response headers that can improve the security posture of an Express application.
Install:
npm install helmet
Then:
const helmet = require("helmet");
app.use(helmet());
This is commonly added to production Express applications.
Morgan Middleware
Morgan is commonly used for HTTP request logging.
Install:
npm install morgan
Then:
const morgan = require("morgan");
app.use(morgan("dev"));
When requests come in, you'll see useful information in the terminal.
For example:
GET /api/users 200
POST /api/users 201
DELETE /api/users/10 204
Instead of building your own request logger, you can use a package like Morgan.
Multer Middleware
Multer is commonly used for handling file uploads.
Install:
npm install multer
Then:
const multer = require("multer");
const upload = multer({
dest: "uploads/"
});
You can use it in a route:
app.post(
"/upload",
upload.single("file"),
(req, res) => {
console.log(req.file);
res.json({
message: "File uploaded successfully"
});
}
);
Here:
upload.single("file")
is middleware.
It processes the uploaded file before the route handler executes.
5. Error-Handling Middleware
Error-handling middleware is a special type of middleware.
It has four parameters:
(err, req, res, next)
Notice the additional:
err
parameter.
Example:
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({
message: "Something went wrong"
});
});
This middleware handles errors passed through the Express middleware chain.
Why Does Error Middleware Have Four Parameters?
Normal middleware:
(req, res, next)
Error-handling middleware:
(err, req, res, next)
The first parameter must be the error:
err
Express recognizes the function as error-handling middleware based on this four-argument signature.
Creating an Error
You can pass an error to the next middleware using:
next(error);
For example:
app.get("/users", (req, res, next) => {
try {
throw new Error("Database failed");
} catch (error) {
next(error);
}
});
Then the error middleware handles it:
app.use((err, req, res, next) => {
console.error(err.message);
res.status(500).json({
message: "Internal server error"
});
});
The flow becomes:
Request
↓
Route
↓
Error occurs
↓
next(error)
↓
Error middleware
↓
Response
Error Middleware Should Usually Be Last
A common pattern is:
app.use(express.json());
app.get("/users", ...);
app.post("/users", ...);
app.use((err, req, res, next) => {
res.status(500).json({
message: "Internal server error"
});
});
Error-handling middleware is normally placed after your routes and other middleware so it can handle errors that occur earlier in the chain.
6. Custom Middleware
Custom middleware is middleware that you create yourself.
For example, let's create a logger:
const logger = (req, res, next) => {
console.log(
`${req.method} ${req.url}`
);
next();
};
app.use(logger);
This is a custom middleware.
You can create custom middleware for many purposes:
- Logging
- Authentication
- Authorization
- Validation
- Request transformation
- Rate limiting
- Permission checks
- Audit logging
Authentication Middleware
One of the most common real-world examples is authentication.
Suppose your API requires a token:
Authorization: Bearer abc123
We can create:
const authenticate = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({
message: "Authentication required"
});
}
// Verify token...
next();
};
Then apply it to a route:
app.get(
"/api/profile",
authenticate,
(req, res) => {
res.json({
message: "Profile data"
});
}
);
The flow becomes:
GET /api/profile
↓
authenticate
↓
Token valid?
↓ ↓
No Yes
↓ ↓
401 next()
↓
Route handler
↓
Response
This is one of the most important uses of middleware in real applications.
Authorization Middleware
Authentication and authorization are different.
Authentication
Answers:
Who are you?
Authorization
Answers:
Are you allowed to perform this action?
For example:
const isAdmin = (req, res, next) => {
if (req.user?.role !== "admin") {
return res.status(403).json({
message: "Access denied"
});
}
next();
};
Then:
app.delete(
"/api/users/:id",
authenticate,
isAdmin,
(req, res) => {
res.json({
message: "User deleted"
});
}
);
Now there are multiple middleware functions:
Request
↓
authenticate
↓
isAdmin
↓
Route handler
↓
Response
Middleware Can Modify req
Middleware doesn't only inspect the request.
It can also add information to it.
For example:
const authenticate = (req, res, next) => {
const user = {
id: 10,
name: "John",
role: "admin"
};
req.user = user;
next();
};
Now the route handler can access:
app.get("/profile", authenticate, (req, res) => {
console.log(req.user);
res.json({
user: req.user
});
});
This pattern is very common with authentication.
Authentication middleware verifies a token and attaches the authenticated user to:
req.user
Then later middleware or controllers can use it.
Middleware Can Modify res
Middleware can also set response information.
For example:
app.use((req, res, next) => {
res.set("X-App-Version", "1.0");
next();
});
Now the response contains the custom header.
Middleware can also set cookies, headers, and other response properties depending on the application.
Middleware Execution Order
Middleware runs in the order in which you register it.
This is extremely important.
Consider:
app.use((req, res, next) => {
console.log("Middleware 1");
next();
});
app.use((req, res, next) => {
console.log("Middleware 2");
next();
});
app.get("/", (req, res) => {
console.log("Route");
res.send("Hello");
});
When you request /, the output will be:
Middleware 1
Middleware 2
Route
The flow is:
Request
↓
Middleware 1
↓
Middleware 2
↓
Route
↓
Response
Middleware Order Can Change Your Application
Consider:
app.get("/users", (req, res) => {
res.json({
users: []
});
});
app.use((req, res, next) => {
console.log("Logger");
next();
});
The logger won't run for the /users request because the route sends the response before the middleware is reached.
Instead:
app.use((req, res, next) => {
console.log("Logger");
next();
});
app.get("/users", (req, res) => {
res.json({
users: []
});
});
Now the logger runs first.
This is why middleware ordering matters.
Multiple Middleware Functions
You can pass multiple middleware functions to a route.
For example:
app.get(
"/api/profile",
authenticate,
isAdmin,
validateRequest,
(req, res) => {
res.json({
message: "Profile"
});
}
);
The execution order is:
authenticate
↓
isAdmin
↓
validateRequest
↓
route handler
Each middleware must call:
next();
if the request should continue.
Middleware Can Stop the Request
Middleware doesn't always have to call next().
For example:
const checkMaintenance = (req, res, next) => {
const maintenanceMode = true;
if (maintenanceMode) {
return res.status(503).json({
message: "Server is under maintenance"
});
}
next();
};
Here the middleware sends the response itself.
The route handler never executes.
Request
↓
checkMaintenance
↓
Maintenance mode?
↓
Yes
↓
503 Response
This is useful for:
- Authentication failures
- Authorization failures
- Validation failures
- Maintenance mode
- Rate limits
Route-Specific Middleware
Middleware doesn't always need to apply globally.
You can attach it to a specific route.
For example:
const authenticate = (req, res, next) => {
console.log("Authentication check");
next();
};
app.get(
"/api/profile",
authenticate,
(req, res) => {
res.json({
message: "Profile"
});
}
);
The authentication middleware only runs for:
/api/profile
It won't automatically run for:
/api/products
Global Middleware vs Route Middleware
Global
app.use(authenticate);
This can apply broadly to requests depending on where and how it is mounted.
Route-specific
app.get(
"/profile",
authenticate,
profileController
);
Only this route uses the middleware.
Choosing between them depends on your application's requirements.
A Practical Middleware Structure
As an application grows, you may create separate middleware files.
For example:
src/
│
├── middleware/
│ ├── auth.js
│ ├── logger.js
│ ├── validation.js
│ └── errorHandler.js
│
├── routes/
│ ├── userRoutes.js
│ └── productRoutes.js
│
├── controllers/
│ ├── userController.js
│ └── productController.js
│
└── server.js
This keeps your application easier to maintain.
Creating a Logger Middleware
Create:
middleware/logger.js
const logger = (req, res, next) => {
console.log(
`${req.method} ${req.originalUrl}`
);
next();
};
module.exports = logger;
Then in server.js:
const logger = require("./middleware/logger");
app.use(logger);
Now all matching requests pass through the logger.
Creating Authentication Middleware
Create:
middleware/auth.js
const authenticate = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({
message: "Authentication required"
});
}
// Token verification would happen here.
next();
};
module.exports = authenticate;
Use it:
const authenticate = require("./middleware/auth");
app.get(
"/api/profile",
authenticate,
(req, res) => {
res.json({
message: "Profile data"
});
}
);
Creating Error-Handling Middleware
Create:
middleware/errorHandler.js
const errorHandler = (err, req, res, next) => {
console.error(err);
res.status(500).json({
message: "Internal server error"
});
};
module.exports = errorHandler;
Then:
const errorHandler = require("./middleware/errorHandler");
app.use(errorHandler);
Again, error-handling middleware should generally be registered after your routes.
Complete Middleware Example
Let's put several pieces together.
const express = require("express");
const app = express();
// Built-in middleware
app.use(express.json());
// Logger middleware
app.use((req, res, next) => {
console.log(
`${req.method} ${req.url}`
);
next();
});
// Authentication middleware
const authenticate = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({
message: "Authentication required"
});
}
next();
};
// Public route
app.get("/api/products", (req, res) => {
res.json({
message: "Products"
});
});
// Protected route
app.get(
"/api/profile",
authenticate,
(req, res) => {
res.json({
message: "Profile"
});
}
);
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({
message: "Internal server error"
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
There are several middleware types working together here:
express.json()
↓
Logger
↓
Route-specific authentication
↓
Route handler
↓
Error handler
Middleware Execution Flow
A useful way to visualize Express middleware is:
HTTP Request
↓
express.json()
↓
Logger
↓
Authentication
↓
Authorization
↓
Validation
↓
Controller
↓
Response
↓
Error Handler
Not every request needs every middleware, but this is a common production-style architecture.
Middleware and Controllers
In a larger Express application, you may separate middleware from business logic.
For example:
router.post(
"/users",
authenticate,
validateUser,
createUser
);
Here:
authenticate
↓
Authentication
validateUser
↓
Input validation
createUser
↓
Business logic / controller
This keeps each piece focused on one responsibility.
Middleware Should Have a Single Responsibility
A good middleware usually does one main thing.
For example:
logger
↓
Log requests
authenticate
↓
Verify authentication
validateUser
↓
Validate user input
errorHandler
↓
Handle errors
Avoid creating one giant middleware that does everything:
const middleware = (req, res, next) => {
// Authentication
// Authorization
// Validation
// Logging
// Database queries
// Business logic
// ...
};
That quickly becomes difficult to maintain.
Smaller middleware functions are usually easier to test and reuse.
Common Middleware Mistakes
1. Forgetting next()
This is probably the most common beginner mistake.
app.use((req, res, next) => {
console.log("Hello");
});
If the middleware doesn't send a response or call next(), the request can get stuck.
Correct:
app.use((req, res, next) => {
console.log("Hello");
next();
});
2. Calling next() After Sending a Response
Avoid:
app.use((req, res, next) => {
res.json({
message: "Unauthorized"
});
next();
});
Once the middleware sends the response, it generally shouldn't continue.
Instead:
app.use((req, res, next) => {
return res.status(401).json({
message: "Unauthorized"
});
});
3. Registering Middleware in the Wrong Order
Consider:
app.get("/users", userController);
app.use(authenticate);
Authentication won't protect /users because the route has already handled the request.
Instead:
app.use(authenticate);
app.get("/users", userController);
Order matters.
4. Forgetting express.json()
If you're expecting:
req.body
from JSON requests, make sure you have:
app.use(express.json());
before the relevant routes.
5. Making Middleware Do Too Much
Don't put all your application logic into middleware.
For example, this is usually not a good design:
app.use(async (req, res, next) => {
// Get user
// Update database
// Validate everything
// Send emails
// Process orders
// ...
});
Middleware should generally handle a specific cross-cutting concern.
Middleware vs Route Handler
This is another useful distinction.
Middleware
Usually performs an intermediate operation:
const logger = (req, res, next) => {
console.log(req.method);
next();
};
Route handler
Usually handles the actual endpoint logic and sends the response:
app.get("/users", (req, res) => {
res.json({
users: []
});
});
In a production application, the route handler may call a controller:
router.get("/users", getUsers);
Middleware Is Like a Pipeline
One simple way to understand middleware is to imagine a pipeline.
Request
↓
┌──────────────┐
│ Logger │
└──────────────┘
↓
┌──────────────┐
│ Auth │
└──────────────┘
↓
┌──────────────┐
│ Validation │
└──────────────┘
↓
┌──────────────┐
│ Controller │
└──────────────┘
↓
Response
Each middleware performs a specific task and then passes control to the next stage.
That's essentially what Express middleware is all about.
Summary of Middleware Types
Let's quickly review the major types.
1. Application-Level Middleware
Attached to the Express app:
app.use(middleware);
Useful for application-wide behavior.
2. Router-Level Middleware
Attached to an Express router:
router.use(middleware);
Useful for specific groups of routes.
3. Built-in Middleware
Provided by Express:
express.json()
express.urlencoded()
express.static()
4. Third-Party Middleware
Installed from npm:
cors
helmet
morgan
multer
5. Error-Handling Middleware
Handles errors:
(err, req, res, next)
6. Custom Middleware
Middleware created by you:
const logger = (req, res, next) => {
console.log("Request");
next();
};
Final Thoughts
Middleware is one of the most important concepts to understand when learning Express.js.
The basic idea is simple:
Request
↓
Middleware
↓
Next Middleware
↓
Route Handler
↓
Response
A middleware function normally looks like:
(req, res, next) => {
// Do something
next();
}
The three important pieces are:
req
↓
Read information from the request
res
↓
Send a response
next()
↓
Continue to the next middleware
As your Express.js applications become more complex, middleware becomes even more useful.
You can create separate middleware for:
Logging
Authentication
Authorization
Validation
File Uploads
Rate Limiting
Security
Error Handling
Instead of putting all of this logic inside every route, middleware allows you to create reusable processing steps.
A typical production API might eventually look like:
Request
↓
CORS
↓
Security
↓
Logger
↓
Authentication
↓
Authorization
↓
Validation
↓
Controller
↓
Service
↓
Database
↓
Response
Once you understand this middleware flow, the architecture of larger Express.js applications becomes much easier to follow.
The key takeaway: middleware is the reusable layer that sits between the incoming request and the final response, allowing you to process, validate, protect, modify, or monitor requests before they reach your application logic.