Router Modules
Putting every route in one file works for a demo, not for a real API. express.Router() creates a mini-application with its own routes and middleware that you mount under a path prefix. Each resource — users, books, orders — gets its own router, usually in its own file.
Creating and mounting a router
// routes/books.js
const { Router } = require('express');
const router = Router();
router.get('/', (req, res) => res.json(listBooks())); // GET /books
router.get('/:id', (req, res) => res.json(findBook(req.params.id))); // GET /books/:id
module.exports = router;
// app.js
app.use('/books', require('./routes/books'));Inside the router, paths are relative to the mount point. The same router could be mounted at /api/v1/books without changing a line.
A runnable multi-router app
Here two routers are defined inline (in a real project each would be its own module):
const express = require('express');
const books = express.Router();
books.get('/', (req, res) => res.json(['Dune', 'Kindred']));
books.get('/:id', (req, res) => res.json({ book: req.params.id }));
const authors = express.Router();
authors.get('/', (req, res) => res.json(['Herbert', 'Butler']));
const app = express();
app.use('/api/books', books);
app.use('/api/authors', authors);
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const p of ['/api/books', '/api/books/7', '/api/authors', '/api/nothing']) {
const res = await fetch(base + p);
console.log(p.padEnd(13), res.status, res.ok ? await res.text() : '');
}
server.close();
});/api/books 200 ["Dune","Kindred"]
/api/books/7 200 {"book":"7"}
/api/authors 200 ["Herbert","Butler"]
/api/nothing 404
Router-level middleware
router.use() only affects requests that reach that router. This is a neat way to protect one area of the API:
const express = require('express');
const admin = express.Router();
admin.use((req, res, next) => {
if (req.get('x-admin-key') !== 'secret') return res.status(401).json({ error: 'admin key required' });
next();
});
admin.get('/stats', (req, res) => res.json({ users: 42 }));
const app = express();
app.get('/public', (req, res) => res.json({ open: true }));
app.use('/admin', admin);
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const calls = [
['/public', {}],
['/admin/stats', {}],
['/admin/stats', { 'x-admin-key': 'secret' }],
];
for (const [p, headers] of calls) {
const res = await fetch(base + p, { headers });
console.log(p.padEnd(12), res.status, await res.text());
}
server.close();
});/public 200 {"open":true}
/admin/stats 401 {"error":"admin key required"}
/admin/stats 200 {"users":42}
req.baseUrl, req.path and req.originalUrl
Inside a mounted router, Express splits the URL for you:
const express = require('express');
const router = express.Router();
router.get('/:id/reviews', (req, res) => {
res.json({ baseUrl: req.baseUrl, path: req.path, originalUrl: req.originalUrl });
});
const app = express();
app.use('/api/books', router);
const server = app.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}/api/books/9/reviews?sort=new`);
console.log(await res.json());
server.close();
});{
baseUrl: '/api/books',
path: '/9/reviews',
originalUrl: '/api/books/9/reviews?sort=new'
}
Parameters from the parent path
If the mount path contains a parameter, the child router can't see it unless you opt in with mergeParams:
const express = require('express');
const reviews = express.Router({ mergeParams: true });
reviews.get('/', (req, res) => res.json({ reviewsOfBook: req.params.bookId }));
const app = express();
app.use('/books/:bookId/reviews', reviews);
const server = app.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}/books/12/reviews`);
console.log(await res.json());
server.close();
});{ reviewsOfBook: '12' }
Without { mergeParams: true }, req.params.bookId would be undefined.
Versioning an API
Routers make versioning painless: keep the old router alive while you build the new one.
app.use('/api/v1', require('./routes/v1'));
app.use('/api/v2', require('./routes/v2'));| Router option | Default | Meaning |
|---|---|---|
mergeParams |
false |
see parent route parameters |
caseSensitive |
false |
treat /Books and /books differently |
strict |
false |
treat /books and /books/ differently |
Tip: A common file layout is
src/routes/<resource>.jsexporting a router, plussrc/routes/index.jsthat mounts them all. See the Project Structure lesson.
Test yourself
A router mounted with app.use('/api/users', router) defines router.get('/:id', …). Which URL reaches it?
- /:id
- /users/5
- /api/users/5
- /api/5
Why would req.params.bookId be undefined in a router mounted at /books/:bookId/reviews?
- Parameters are not allowed in mount paths
- The router was created without
mergeParams: true - You must use
req.queryinstead - Routers can't read params at all
What does router.use(authCheck) protect?
- The whole app
- Only requests handled by that router
- Only GET requests
- Nothing until
app.listen