Router-Level Middleware in Express.js
Router-level middleware allows us to apply middleware to a specific Express Router instead of registering every middleware directly on the main Express application.
In a large application, we may have different sections such as Users, Products, Admin, and Orders. Each section can have its own routes and middleware. Router-level middleware helps us organize these related routes and apply common logic to them.
Express provides the express.Router() function to
create a router. We can register middleware on that router using
router.use() or use middleware for a specific route.
1. What Is Router-Level Middleware?
Router-level middleware is middleware registered on an Express Router instance. It works similarly to application-level middleware, but its scope is associated with a particular router.
For example, suppose an application has a separate router for products. We can register middleware on the product router to log requests before they reach the product route handlers.
const express = require('express');
const app = express();
const router = express.Router();
// Router-level middleware
router.use((req, res, next) => {
console.log('Product router middleware executed');
next();
});
// Router route
router.get('/list', (req, res) => {
res.send('Product List');
});
// Mount router on the application
app.use('/products', router);
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Here, express.Router() creates a separate router.
The router.use() method registers middleware on that
router, and app.use('/products', router) mounts it
under the /products path.
Therefore, when a client requests
http://localhost:3000/products/list, the router
middleware executes before the matching route handler.
/list
inside the router, but the complete URL path becomes
/products/list after the router is mounted.
2. Why Do We Need Router-Level Middleware?
In a small application, we may write all routes directly inside
app.js. But when an application grows, managing every
route and its middleware in one file becomes difficult.
Router-level middleware helps us group related routes together and apply common processing logic to that group.
| Use Case | Explanation |
|---|---|
| User Routes | Apply common checks or logging to user-related routes. |
| Product Routes | Process requests related to products in one router. |
| Admin Routes | Apply authentication and authorization middleware where required. |
| Order Routes | Keep order-related request processing together. |
| Maintainability | Separate route logic into smaller, understandable modules. |
3. Diagram 1: How Router-Level Middleware Works
The following diagram shows how a client request moves through the main Express application and into a mounted router.
Client / Browser
Requests /products/list
Express Application (app.js)
Receives the incoming HTTP request
Mounted Router
app.use('/products', productRouter)
Router Middleware
router.use((req, res, next) => ...)
Logs or checks the request
Router Route Handler
router.get('/list', ...)
Processes the matching route
HTTP Response
Sends Product List to the client
Step-by-step explanation:
- The client sends a request to
/products/list. - The Express application receives the request.
- The mounted router matches the
/productsprefix. - The router middleware runs in registration order.
- Calling
next()passes control forward. - The matching route handler sends the response.
4. Creating a Router Using express.Router()
The express.Router() function creates a router object.
We can define related routes on this object and mount it in the
main application.
Example:
const express = require('express');
const app = express();
const userRouter = express.Router();
userRouter.get('/', (req, res) => {
res.send('User Home Page');
});
userRouter.get('/profile', (req, res) => {
res.send('User Profile Page');
});
app.use('/users', userRouter);
app.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example, the router contains two routes. Because the router
is mounted at /users, the complete URLs become:
| Router Route | Complete URL Path | Response |
|---|---|---|
/ |
/users |
User Home Page |
/profile |
/users/profile |
User Profile Page |
5. Registering Middleware with router.use()
The router.use() method registers middleware on a
router. If no path is supplied, the middleware can run for
requests handled by that router, according to the order in which
middleware and routes are registered.
const express = require('express');
const app = express();
const userRouter = express.Router();
// Middleware for this router
userRouter.use((req, res, next) => {
console.log('User router middleware executed');
next();
});
userRouter.get('/', (req, res) => {
res.send('User Home Page');
});
userRouter.get('/profile', (req, res) => {
res.send('User Profile Page');
});
app.use('/users', userRouter);
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Test these URLs:
http://localhost:3000/usershttp://localhost:3000/users/profile
Example terminal output:
Server running on port 3000
User router middleware executed
User router middleware executed
Each request reaching the router passes through its middleware before reaching the corresponding route handler. The two log lines represent the two example requests.
6. Diagram 2: Middleware for Multiple Routers
An application can contain multiple routers. Each router can have its own middleware and route handlers, allowing the application to separate different features.
Express Application
app.js
User Router
/users
Product Router
/products
Explanation:
- The main Express application mounts the user router at
/users. - The user router can apply middleware to user-related routes.
- The product router is mounted at
/products. - The product router can apply different middleware to product-related routes.
- Each router keeps its related route logic organized separately.
7. Complete Example with Router-Level Middleware
Let us create a small application that uses a product router and logs requests made to its routes.
Step 1: Create app.js
const express = require('express');
const app = express();
const productRouter = express.Router();
// Router-level middleware
productRouter.use((req, res, next) => {
console.log(`${req.method} ${req.originalUrl}`);
next();
});
// Product routes
productRouter.get('/', (req, res) => {
res.send('All Products');
});
productRouter.get('/:id', (req, res) => {
res.send(`Product ID: ${req.params.id}`);
});
// Mount the router
app.use('/products', productRouter);
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Step 2: Install Express and run the application
npm init -y
npm install express
node app.js
Step 3: Test the endpoints
| Request URL | Browser Response | Terminal Log |
|---|---|---|
/products |
All Products | GET /products |
/products/101 |
Product ID: 101 | GET /products/101 |
The middleware logs the original request URL. The route
/:id captures the product ID through
req.params.id.
8. Application-Level vs Router-Level Middleware
| Application-Level | Router-Level |
|---|---|
| Registered on the Express application. | Registered on an Express Router. |
Commonly uses app.use(). |
Commonly uses router.use(). |
| Can apply common logic across the application. | Can apply common logic to a group of related routes. |
| Example: general request logging. | Example: logging requests to product routes. |
Important Points to Remember
express.Router()creates a router instance.router.use()registers middleware on a router.app.use('/prefix', router)mounts a router at a path.- Router middleware executes in registration order.
next()passes control to the next handler.- Different routers can have different middleware.
- The mounted path is combined with the route path.
- Router middleware alone does not provide authentication or authorization.
Summary
Router-level middleware allows us to register middleware on an Express Router instead of applying it directly to the main application.
By using express.Router(), router.use(),
and app.use(), we can group related routes,
apply common processing logic, and keep larger applications
organized and maintainable.