What does express.Router() do?
1. What express.Router() does
express.Router()creates a "mini application" (a mini Express instance) that works the same wayappdoes, but is meant for grouping routes and middleware.
The idea:
instead of describing every route in app.js,
you can split them across files and import them into the main application.
An example without Router (everything in one file):
const express = require('express');
const app = express();
app.get('/users', (req, res) => res.send('List of users'));
app.get('/products', (req, res) => res.send('List of products'));
app.listen(3000);The downside: the code quickly gets unwieldy.
2. An example using express.Router()
Let's create two separate files for routes:
routes/users.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('List of users');
});
router.get('/:id', (req, res) => {
res.send(`User with ID: ${req.params.id}`);
});
module.exports = router;routes/products.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('List of products');
});
router.post('/', (req, res) => {
res.send('Product created');
});
module.exports = router;app.js
const express = require('express');
const app = express();
const usersRouter = require('./routes/users');
const productsRouter = require('./routes/products');
// Mount the routers with a prefix
app.use('/users', usersRouter);
app.use('/products', productsRouter);
app.listen(3000, () => console.log('Server running'));Now:
GET /users→ "List of users"GET /users/42→ "User with ID: 42"GET /products→ "List of products"POST /products→ "Product created"
3. How Router works internally
Every Router is a middleware instance
that holds its own set of routes and in-between handlers.
When Express receives a request:
- It checks whether the path matches (
/users,/products, etc.). - If it matches, the request is handed to the inner Router, which runs its own little "mini Event Loop" of routes and middleware.
4. Router supports everything app does
| Feature | Works in Router? | Example |
|---|---|---|
| Middleware | Yes | router.use(authMiddleware) |
| Routes | Yes | router.get('/', handler) |
| Parameters | Yes | router.param('id', callback) |
| Sub-routers | Yes | router.use('/admin', adminRouter) |
5. Why use Router, the advantages
| Advantage | Explanation |
|---|---|
| Modularity | Lets you split the app into logical parts (users, products, orders, etc.) |
| Reusability | One Router can be mounted into different applications |
| Readability and structure | The code stays clean and easy to navigate |
| Local middleware | Middleware can apply only to a specific group of routes |
| Testability | Makes it easier to write unit tests for individual API modules |
6. Example: middleware for a single Router only
const router = express.Router();
function authMiddleware(req, res, next) {
if (req.headers.token === '123') next();
else res.status(401).send('Access denied');
}
router.use(authMiddleware); // applies only to this Router's routes
router.get('/secret', (req, res) => {
res.send('The secret zone');
});
module.exports = router;Now the authorization check applies only to /secret,
and doesn't affect the rest of the application.
7. Summary
express.Router()is a mini Express application that lets you group routes and middleware for a specific part of the API.It's used to:
- organize code (splitting it into modules);
- mount it with a prefix (
app.use('/api/users', usersRouter));- add local middleware;
- make maintenance and testing simpler.
Almost every sizable Express application is built on
Router().
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.