- Spec files
npm-express
Describes: pkg:npm/express@5.1.x
- Description
- Fast, unopinionated, minimalist web framework for Node.js
- Author
- tessl
- Last updated
router.md docs/
1# Routing System23Router and Route classes for organizing application endpoints, handling HTTP methods, and managing route parameters.45## Capabilities67### Router Creation89Create modular route handlers that can be mounted on applications or other routers.1011```javascript { .api }12/**13* Create new router instance14* @param {object} options - Router configuration options (optional)15* @returns {Router} Router instance16*/17function Router(options?: object): Router;18```1920**Router Options:**2122```javascript { .api }23interface RouterOptions {24/**25* Enable case sensitivity (disabled by default)26*/27caseSensitive?: boolean;2829/**30* Preserve req.params values from parent router31*/32mergeParams?: boolean;3334/**35* Enable strict routing (disabled by default)36*/37strict?: boolean;38}39```4041**Usage Examples:**4243```javascript44const express = require('express');45const router = express.Router();4647// Basic router creation48const apiRouter = express.Router();49const userRouter = express.Router({ mergeParams: true });5051// Router with options52const strictRouter = express.Router({53strict: true, // /foo and /foo/ are different54caseSensitive: true, // /Foo and /foo are different55mergeParams: true // Preserve parent route params56});57```5859### Router Middleware and Routing6061Mount middleware and define routes on router instances.6263```javascript { .api }64/**65* Mount middleware function(s) on router66* @param {...Function} handlers - Middleware functions67* @returns {Router} Router instance for chaining68*/69use(...handlers: Function[]): Router;7071/**72* Mount middleware function(s) at specific path73* @param {string} path - Path pattern74* @param {...Function} handlers - Middleware functions75* @returns {Router} Router instance for chaining76*/77use(path: string, ...handlers: Function[]): Router;7879/**80* Create new route for specified path81* @param {string} path - Route path pattern82* @returns {Route} Route instance for method chaining83*/84route(path: string): Route;8586/**87* Handle all HTTP methods for specified path88* @param {string} path - Route path pattern89* @param {...Function} handlers - Route handler functions90* @returns {Router} Router instance for chaining91*/92all(path: string, ...handlers: Function[]): Router;9394// HTTP method handlers95get(path: string, ...handlers: Function[]): Router;96post(path: string, ...handlers: Function[]): Router;97put(path: string, ...handlers: Function[]): Router;98delete(path: string, ...handlers: Function[]): Router;99patch(path: string, ...handlers: Function[]): Router;100options(path: string, ...handlers: Function[]): Router;101head(path: string, ...handlers: Function[]): Router;102```103104**Usage Examples:**105106```javascript107const express = require('express');108const router = express.Router();109110// Router-level middleware111router.use((req, res, next) => {112console.log('Router middleware executed');113next();114});115116// Path-specific middleware117router.use('/protected', authenticateMiddleware);118119// Route handlers120router.get('/', (req, res) => {121res.send('Router home');122});123124router.post('/users', (req, res) => {125res.json({ message: 'User created' });126});127128// Route chaining129router.route('/books')130.get((req, res) => res.send('Get books'))131.post((req, res) => res.send('Create book'))132.put((req, res) => res.send('Update book'));133134// Mount router on application135const app = express();136app.use('/api', router);137```138139### Router Parameter Processing140141Add callbacks that trigger when route parameters are present in router paths.142143```javascript { .api }144/**145* Add callback for route parameter146* @param {string} name - Parameter name147* @param {Function} fn - Callback function148* @returns {Router} Router instance for chaining149*/150param(name: string, fn: Function): Router;151152/**153* Add callback for multiple route parameters154* @param {string[]} names - Array of parameter names155* @param {Function} fn - Callback function156* @returns {Router} Router instance for chaining157*/158param(names: string[], fn: Function): Router;159```160161**Usage Examples:**162163```javascript164const userRouter = express.Router();165166// Parameter callback for user ID167userRouter.param('userId', (req, res, next, id) => {168// Load user data169User.findById(id, (err, user) => {170if (err) return next(err);171if (!user) return next(new Error('User not found'));172req.user = user;173next();174});175});176177// Routes using the parameter178userRouter.get('/:userId', (req, res) => {179res.json(req.user); // User loaded by param callback180});181182userRouter.put('/:userId', (req, res) => {183// Update req.user with req.body data184req.user.update(req.body, (err) => {185if (err) return res.status(500).json({ error: err.message });186res.json(req.user);187});188});189190// Mount the router191app.use('/users', userRouter);192```193194### Route Creation and Management195196Create individual routes for more granular control over HTTP method handling.197198```javascript { .api }199/**200* Create new route instance for specified path201* @param {string} path - Route path pattern202* @returns {Route} Route instance203*/204function Route(path: string): Route;205```206207**Route Methods:**208209```javascript { .api }210/**211* Handle all HTTP methods for this route212* @param {...Function} handlers - Route handler functions213* @returns {Route} Route instance for chaining214*/215all(...handlers: Function[]): Route;216217// HTTP method handlers for individual route218get(...handlers: Function[]): Route;219post(...handlers: Function[]): Route;220put(...handlers: Function[]): Route;221delete(...handlers: Function[]): Route;222patch(...handlers: Function[]): Route;223options(...handlers: Function[]): Route;224head(...handlers: Function[]): Route;225```226227**Usage Examples:**228229```javascript230// Create route directly231const userRoute = new express.Route('/users/:id');232233// Add handlers to the route234userRoute235.get((req, res) => {236res.json({ message: 'Get user', id: req.params.id });237})238.put((req, res) => {239res.json({ message: 'Update user', id: req.params.id });240})241.delete((req, res) => {242res.json({ message: 'Delete user', id: req.params.id });243});244245// More commonly, routes are created via app.route() or router.route()246app.route('/products/:id')247.get(getProduct)248.put(updateProduct)249.delete(deleteProduct);250```251252### Router Mounting and Organization253254Organize routes into modular components and mount them on applications.255256**Usage Examples:**257258```javascript259// User routes module (users.js)260const express = require('express');261const router = express.Router();262263router.get('/', getAllUsers);264router.get('/:id', getUser);265router.post('/', createUser);266router.put('/:id', updateUser);267router.delete('/:id', deleteUser);268269module.exports = router;270271// Product routes module (products.js)272const express = require('express');273const router = express.Router();274275router.get('/', getAllProducts);276router.get('/:id', getProduct);277router.post('/', createProduct);278279module.exports = router;280281// Main application282const express = require('express');283const userRoutes = require('./routes/users');284const productRoutes = require('./routes/products');285286const app = express();287288// Mount routers289app.use('/api/users', userRoutes);290app.use('/api/products', productRoutes);291292// Nested router mounting293const apiRouter = express.Router();294apiRouter.use('/users', userRoutes);295apiRouter.use('/products', productRoutes);296app.use('/api/v1', apiRouter);297```298299### Route Path Patterns300301Express routers support various path pattern syntaxes for flexible route matching.302303**Path Pattern Examples:**304305```javascript306// String patterns307router.get('/users', handler); // Exact match308router.get('/users/*', handler); // Wildcard309router.get('/files/*.*', handler); // File with extension310311// String patterns with parameters312router.get('/users/:id', handler); // Single parameter313router.get('/users/:id/posts/:postId', handler); // Multiple parameters314router.get('/users/:id?', handler); // Optional parameter315316// RegExp patterns317router.get(/.*fly$/, handler); // Ends with 'fly'318router.get(/users\/(\d+)/, handler); // Users with numeric ID319320// Array of patterns321router.get(['/users', '/people'], handler); // Multiple exact matches322```323324**Parameter Access:**325326```javascript327router.get('/users/:userId/posts/:postId', (req, res) => {328const { userId, postId } = req.params;329console.log(`User: ${userId}, Post: ${postId}`);330res.json({ userId, postId });331});332333// With optional parameters334router.get('/posts/:year/:month?', (req, res) => {335const { year, month } = req.params;336// month will be undefined if not provided337res.json({ year, month: month || 'all' });338});339```340341### Error Handling in Routers342343Handle errors within router middleware and route handlers.344345```javascript { .api }346/**347* Error handling middleware signature348* @param {Error} err - Error object349* @param {Request} req - Request object350* @param {Response} res - Response object351* @param {NextFunction} next - Next function352*/353type ErrorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => void;354```355356**Usage Examples:**357358```javascript359const router = express.Router();360361// Route with error handling362router.get('/users/:id', async (req, res, next) => {363try {364const user = await User.findById(req.params.id);365if (!user) {366const error = new Error('User not found');367error.status = 404;368return next(error);369}370res.json(user);371} catch (error) {372next(error); // Pass error to error handler373}374});375376// Router-level error handler377router.use((err, req, res, next) => {378const status = err.status || 500;379res.status(status).json({380error: {381message: err.message,382status: status383}384});385});386```387388### Router Properties389390```javascript { .api }391/**392* Router parameter callbacks393*/394params: { [key: string]: Function[] };395396/**397* Case sensitivity setting398*/399caseSensitive: boolean;400401/**402* Merge parameters setting403*/404mergeParams: boolean;405406/**407* Strict routing setting408*/409strict: boolean;410```411412**Usage Examples:**413414```javascript415const router = express.Router({ mergeParams: true });416417// Check router configuration418console.log('Merge params:', router.mergeParams); // true419console.log('Case sensitive:', router.caseSensitive); // false (default)420console.log('Strict routing:', router.strict); // false (default)421```