Express router: grouping routes
Once you have more than two routes, putting them all on app starts to feel cramped. Express Router lets you group related routes in their own file and mount the whole group at a prefix.
import { Router } from 'express';
import * as bookController from '../controllers/book.controller';
export const bookRouter = Router();
bookRouter.get('/', bookController.getBooksHandler);
bookRouter.get('/:id', bookController.getBookHandler);
bookRouter.post('/', bookController.createBookHandler);
bookRouter.delete('/:id', bookController.deleteBookHandler);A router is just a mini Express app you can hand off elsewhere.
import express from 'express';
import { bookRouter } from './routes/book.routes';
export const app = express();
app.use(express.json()); // parse JSON bodies
app.use('/api/books', bookRouter); // mount the router
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});Mount the router at /api/books and every route inside it picks up the prefix.
Look at how the URLs compose. The router declares its routes as / and /:id. The mount point is /api/books. When you put them together: GET /api/books, GET /api/books/:id, POST /api/books, DELETE /api/books/:id. The router does not need to know its own prefix. That is the win.
Quiz: Quiz
Loading practiceโฆ