Express Router
As an Express app grows, putting all routes in one file becomes hard to navigate. express.Router() lets you split routes into separate files grouped by resource, then mount them in the main app file.
What is express.Router()?
express.Router() creates a mini Express app that handles routes for a specific path. You define routes on the router, export it, and mount it in app.js with app.use().
Basic usage
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Hello from the router');
});
module.exports = router;
Full example: splitting a people resource
Starting point: everything in app.js
const express = require('express');
const app = express();
const { getPeople, createPerson, updatePerson, deletePerson } =
require('../controllers/people');
app.get('/people', getPeople);
app.post('/people', createPerson);
app.put('/people/:id', updatePerson);
app.delete('/people/:id', deletePerson);
app.listen(5000, () => {
console.log('Server is listening on port 5000');
});
Step 1: create a routes folder
nodeapp/
routes/
people.js
app.js
Step 2: create the people route file
Move the people routes into routes/people.js. Replace app with router. Because the router will be mounted at /people, drop that prefix from each path.
const express = require('express');
const router = express.Router();
const { getPeople, createPerson, updatePerson, deletePerson } =
require('../controllers/people');
router.route('/').get(getPeople).post(createPerson);
router.route('/:id').put(updatePerson).delete(deletePerson);
module.exports = router;
Note: routes in a router file use paths relative to the mount point. Mounting at /people means a route for / in this file handles /people, and /:id handles /people/:id.
Step 3: mount the router in app.js
const express = require('express');
const app = express();
const peopleRouter = require('./routes/people');
app.use('/people', peopleRouter);
app.listen(5000, () => {
console.log('Server is listening on port 5000');
});
Restart the server. All people routes work exactly as before, but the code is now easier to find and maintain.
What to read next
- Middleware : add middleware at the router level
- Routing : how individual route methods work