Express.js Router
express.Router() creates a modular, mountable route handler for an Express application. A router can contain its own routes and middleware, allowing related endpoints to be moved out of the main app.js file.
A router is often described as a mini application because it supports routing methods such as get(), post(), put(), and delete(), along with router-level middleware. However, it does not start its own server. It must be mounted on an Express application or another router.
var router = express.Router()
Why use express.Router() in an Express application?
Defining every endpoint in one file becomes difficult to maintain as an application grows. Express Router lets you group routes by feature or resource, such as users, products, orders, or authentication.
- Keep related routes in separate files.
- Apply middleware only to a specific group of routes.
- Mount multiple routers under different base paths.
- Reuse router modules in larger Express applications.
- Make route files easier to read, test, and maintain.
Create an Express.js Router
In the following example, an API router is created in a separate file. The router contains middleware and two GET routes.
router1.js
var express = require('express')
var router1 = express.Router()
// middleware that is specific to this router
router1.use(function timeLog (req, res, next) {
console.log('Requested URI Path : ', req.url)
next()
})
// define the home page route
router1.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router1.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router1
The router is created with express.Router(). The call to router1.use() registers router-level middleware, and the calls to router1.get() define routes relative to the router’s mount path.
The final statement exports the router so that it can be imported and mounted in app.js.
Mount the Express Router with app.use()
app.js
var express = require('express')
var app = express()
var router1 = require('./router1')
app.use('/api/', router1)
// start the server
var server = app.listen(8000, function(){
console.log('Listening on port 8000...')
})
The statement app.use('/api/', router1) mounts router1 at the base path /api/. Express removes the mount path before matching routes inside the router.
- The router path
/becomes/api/. - The router path
/aboutbecomes/api/about.
When you open http://localhost:8000/api/, Express matches the router’s / route and returns Birds home page.

When you open http://localhost:8000/api/about/, Express matches the router’s /about route and returns About birds.

Terminal Log

The terminal log is produced by the router-level middleware. Because the middleware calls next(), Express continues to the matching route handler after logging the request path.
Understand the Express Router execution flow
For a request to GET /api/about, Express processes the request in this order:
- The request reaches the Express application.
app.use('/api/', router1)matches the/apiprefix.- Express forwards the remaining path,
/about, torouter1. - The router-level middleware runs and calls
next(). - The
router1.get('/about', ...)handler matches the request. - The route handler sends
About birdsas the response.
Router middleware and routes run in the order in which they are registered. Middleware that does not send a response must call next(); otherwise, the request will not reach the next matching handler.
Add GET, POST, PUT, and DELETE routes to an Express Router
A router can handle different HTTP methods in the same way as the main Express application.
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('List all users')
})
router.post('/', function (req, res) {
res.send('Create a user')
})
router.put('/:id', function (req, res) {
res.send('Replace user ' + req.params.id)
})
router.delete('/:id', function (req, res) {
res.send('Delete user ' + req.params.id)
})
module.exports = router
If this router is mounted with app.use('/users', router), the resulting endpoints include GET /users, POST /users, PUT /users/:id, and DELETE /users/:id.
Use route parameters in express.Router()
Route parameters capture dynamic values from a URL. A parameter starts with a colon, as in /:id.
router.get('/:id', function (req, res) {
res.send('User ID: ' + req.params.id)
})
When the mounted route receives a request such as GET /users/42, the value 42 is available through req.params.id.
Apply middleware to specific Express Router routes
Middleware can be applied to every route in a router or only to selected routes. The following example protects one route with an authentication middleware function.
function requireLogin(req, res, next) {
if (req.headers.authorization) {
next()
return
}
res.status(401).send('Authentication required')
}
router.get('/profile', requireLogin, function (req, res) {
res.send('User profile')
})
The requireLogin function runs only for the /profile route. If authentication succeeds, it calls next(); otherwise, it sends a 401 response.
Mount multiple routers under separate base paths
Larger applications commonly use one router file for each resource or feature.
var usersRouter = require('./routes/users')
var productsRouter = require('./routes/products')
var ordersRouter = require('./routes/orders')
app.use('/users', usersRouter)
app.use('/products', productsRouter)
app.use('/orders', ordersRouter)
Each router handles paths relative to its own mount point. For example, a router.get('/:id') route in productsRouter responds at /products/:id.
Use router.route() for handlers sharing the same path
The router.route() method groups handlers that use the same route path but different HTTP methods.
router.route('/:id')
.get(function (req, res) {
res.send('Get user ' + req.params.id)
})
.put(function (req, res) {
res.send('Update user ' + req.params.id)
})
.delete(function (req, res) {
res.send('Delete user ' + req.params.id)
})
This structure avoids repeating the same path for each HTTP method.
Handle unmatched requests inside an Express Router
A router can include its own fallback handler. Place it after all valid router routes so that it runs only when no route matches.
router.use(function (req, res) {
res.status(404).send('API route not found')
})
If the router is mounted at /api, this handler returns a router-specific 404 response for unmatched paths under /api.
Express Router questions
What is the difference between app and Router in Express?
The Express application object can start the HTTP server and configure application-wide middleware. A router cannot listen on a port by itself; it defines modular routes and middleware that must be mounted on an application or another router.
What does app.use(‘/api’, router) do?
It mounts the router under the /api</code path. A route defined as <code>router.get('/users') then responds at /api/users.
Can an Express Router have its own middleware?
Yes. Use router.use() for middleware that should run for multiple router routes, or pass middleware directly to a route when it should run only for that endpoint.
Why is an Express Router route not matching?
Check the router’s mount path, the route’s relative path, the HTTP method, and the order in which middleware and routes are registered. Also confirm that earlier middleware calls next() when it does not send a response.
Express Router editorial QA checklist
- Confirm that every router module exports the router object.
- Verify that each router is imported and mounted with the intended base path.
- Check the combined mount path and router path for every documented endpoint.
- Ensure router middleware either sends a response or calls
next(). - Place router-specific 404 handlers after all valid router routes.
Express.js Router summary
express.Router() provides a practical way to organize routes and middleware into separate modules. Create a router, define paths relative to that router, export it, and mount it with app.use(). The final endpoint is formed by combining the application’s mount path with the path defined inside the router.
TutorialKart.com