Express Router
What you’ll learn
- How to create routers with
express.Router(). - How to split routes into modular feature files.
- How to mount routers with path prefixes using
app.use(). - How to avoid common router configuration mistakes.
Overview
Express Router helps you organize routes by feature so applications stay maintainable as they grow.
Modular structure
Keep user, admin, product, and auth routes in separate files.
Shared middleware
Attach middleware once at router level for all grouped routes.
Mount prefixes
Use app.use('/api/users', userRouter) to compose full route paths.
Syntax
javascript
const router = express.Router();
router.get('/', handler);
router.post('/', handler);
app.use('/prefix', router);- Create router instance with
express.Router(). - Register route methods on router object.
- Mount router into app with
app.use().
1
Create and export a router module
javascript
const express = require('express');
const router = express.Router();
router.get('/', function (req, res) {
res.send('Users home');
});
module.exports = router;2
Mount router in main app
javascript
const express = require('express');
const userRouter = require('./routes/users');
const app = express();
app.use('/users', userRouter);📋 Router vs app.route()
| API | Purpose | Typical scope |
|---|---|---|
express.Router() | Modular route container | Feature-level route files |
app.route() | Method chain for one path | Single route grouping |
🧪 Testing checklist
- Verify mounted prefix combines correctly with router paths.
- Confirm router-level middleware executes in expected order.
- Test route params and query parsing inside router handlers.
- Check unknown routes return proper 404 behavior.
Pitfalls to avoid
Wrong mount path
Broken URLs
Double-check app.use('/prefix', router) path composition.
Too much logic in one file
Hard maintenance
Split routers by domain/feature as app grows.
Middleware confusion
Unexpected flow
Be explicit about router-level versus route-level middleware order.
❓ FAQ
Router is a mini-application object that lets you group related routes and middleware into modules.
Router keeps code organized by feature, improves readability, and makes large apps easier to maintain.
Create a router with express.Router(), export it, then mount it using app.use('/prefix', router).
Yes. You can attach middleware globally to the router or per-route within that router module.
Use paths like /users/:id inside the router; mounted prefixes combine with local route paths.
Summary
- Core idea: Router modules keep Express apps modular and scalable.
- Usage: define routes in router files and mount with
app.use(). - Practice: organize routers by feature and manage middleware order carefully.
Did you know?
express.Router() creates mini-app route modules, helping split large Express applications into maintainable parts.
4 people found this page helpful
