npm-express

Description
Fast, unopinionated, minimalist web framework for Node.js
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-express@5.1.0

router.md docs/

1
# Routing System
2
3
Router and Route classes for organizing application endpoints, handling HTTP methods, and managing route parameters.
4
5
## Capabilities
6
7
### Router Creation
8
9
Create modular route handlers that can be mounted on applications or other routers.
10
11
```javascript { .api }
12
/**
13
* Create new router instance
14
* @param {object} options - Router configuration options (optional)
15
* @returns {Router} Router instance
16
*/
17
function Router(options?: object): Router;
18
```
19
20
**Router Options:**
21
22
```javascript { .api }
23
interface RouterOptions {
24
/**
25
* Enable case sensitivity (disabled by default)
26
*/
27
caseSensitive?: boolean;
28
29
/**
30
* Preserve req.params values from parent router
31
*/
32
mergeParams?: boolean;
33
34
/**
35
* Enable strict routing (disabled by default)
36
*/
37
strict?: boolean;
38
}
39
```
40
41
**Usage Examples:**
42
43
```javascript
44
const express = require('express');
45
const router = express.Router();
46
47
// Basic router creation
48
const apiRouter = express.Router();
49
const userRouter = express.Router({ mergeParams: true });
50
51
// Router with options
52
const strictRouter = express.Router({
53
strict: true, // /foo and /foo/ are different
54
caseSensitive: true, // /Foo and /foo are different
55
mergeParams: true // Preserve parent route params
56
});
57
```
58
59
### Router Middleware and Routing
60
61
Mount middleware and define routes on router instances.
62
63
```javascript { .api }
64
/**
65
* Mount middleware function(s) on router
66
* @param {...Function} handlers - Middleware functions
67
* @returns {Router} Router instance for chaining
68
*/
69
use(...handlers: Function[]): Router;
70
71
/**
72
* Mount middleware function(s) at specific path
73
* @param {string} path - Path pattern
74
* @param {...Function} handlers - Middleware functions
75
* @returns {Router} Router instance for chaining
76
*/
77
use(path: string, ...handlers: Function[]): Router;
78
79
/**
80
* Create new route for specified path
81
* @param {string} path - Route path pattern
82
* @returns {Route} Route instance for method chaining
83
*/
84
route(path: string): Route;
85
86
/**
87
* Handle all HTTP methods for specified path
88
* @param {string} path - Route path pattern
89
* @param {...Function} handlers - Route handler functions
90
* @returns {Router} Router instance for chaining
91
*/
92
all(path: string, ...handlers: Function[]): Router;
93
94
// HTTP method handlers
95
get(path: string, ...handlers: Function[]): Router;
96
post(path: string, ...handlers: Function[]): Router;
97
put(path: string, ...handlers: Function[]): Router;
98
delete(path: string, ...handlers: Function[]): Router;
99
patch(path: string, ...handlers: Function[]): Router;
100
options(path: string, ...handlers: Function[]): Router;
101
head(path: string, ...handlers: Function[]): Router;
102
```
103
104
**Usage Examples:**
105
106
```javascript
107
const express = require('express');
108
const router = express.Router();
109
110
// Router-level middleware
111
router.use((req, res, next) => {
112
console.log('Router middleware executed');
113
next();
114
});
115
116
// Path-specific middleware
117
router.use('/protected', authenticateMiddleware);
118
119
// Route handlers
120
router.get('/', (req, res) => {
121
res.send('Router home');
122
});
123
124
router.post('/users', (req, res) => {
125
res.json({ message: 'User created' });
126
});
127
128
// Route chaining
129
router.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'));
133
134
// Mount router on application
135
const app = express();
136
app.use('/api', router);
137
```
138
139
### Router Parameter Processing
140
141
Add callbacks that trigger when route parameters are present in router paths.
142
143
```javascript { .api }
144
/**
145
* Add callback for route parameter
146
* @param {string} name - Parameter name
147
* @param {Function} fn - Callback function
148
* @returns {Router} Router instance for chaining
149
*/
150
param(name: string, fn: Function): Router;
151
152
/**
153
* Add callback for multiple route parameters
154
* @param {string[]} names - Array of parameter names
155
* @param {Function} fn - Callback function
156
* @returns {Router} Router instance for chaining
157
*/
158
param(names: string[], fn: Function): Router;
159
```
160
161
**Usage Examples:**
162
163
```javascript
164
const userRouter = express.Router();
165
166
// Parameter callback for user ID
167
userRouter.param('userId', (req, res, next, id) => {
168
// Load user data
169
User.findById(id, (err, user) => {
170
if (err) return next(err);
171
if (!user) return next(new Error('User not found'));
172
req.user = user;
173
next();
174
});
175
});
176
177
// Routes using the parameter
178
userRouter.get('/:userId', (req, res) => {
179
res.json(req.user); // User loaded by param callback
180
});
181
182
userRouter.put('/:userId', (req, res) => {
183
// Update req.user with req.body data
184
req.user.update(req.body, (err) => {
185
if (err) return res.status(500).json({ error: err.message });
186
res.json(req.user);
187
});
188
});
189
190
// Mount the router
191
app.use('/users', userRouter);
192
```
193
194
### Route Creation and Management
195
196
Create individual routes for more granular control over HTTP method handling.
197
198
```javascript { .api }
199
/**
200
* Create new route instance for specified path
201
* @param {string} path - Route path pattern
202
* @returns {Route} Route instance
203
*/
204
function Route(path: string): Route;
205
```
206
207
**Route Methods:**
208
209
```javascript { .api }
210
/**
211
* Handle all HTTP methods for this route
212
* @param {...Function} handlers - Route handler functions
213
* @returns {Route} Route instance for chaining
214
*/
215
all(...handlers: Function[]): Route;
216
217
// HTTP method handlers for individual route
218
get(...handlers: Function[]): Route;
219
post(...handlers: Function[]): Route;
220
put(...handlers: Function[]): Route;
221
delete(...handlers: Function[]): Route;
222
patch(...handlers: Function[]): Route;
223
options(...handlers: Function[]): Route;
224
head(...handlers: Function[]): Route;
225
```
226
227
**Usage Examples:**
228
229
```javascript
230
// Create route directly
231
const userRoute = new express.Route('/users/:id');
232
233
// Add handlers to the route
234
userRoute
235
.get((req, res) => {
236
res.json({ message: 'Get user', id: req.params.id });
237
})
238
.put((req, res) => {
239
res.json({ message: 'Update user', id: req.params.id });
240
})
241
.delete((req, res) => {
242
res.json({ message: 'Delete user', id: req.params.id });
243
});
244
245
// More commonly, routes are created via app.route() or router.route()
246
app.route('/products/:id')
247
.get(getProduct)
248
.put(updateProduct)
249
.delete(deleteProduct);
250
```
251
252
### Router Mounting and Organization
253
254
Organize routes into modular components and mount them on applications.
255
256
**Usage Examples:**
257
258
```javascript
259
// User routes module (users.js)
260
const express = require('express');
261
const router = express.Router();
262
263
router.get('/', getAllUsers);
264
router.get('/:id', getUser);
265
router.post('/', createUser);
266
router.put('/:id', updateUser);
267
router.delete('/:id', deleteUser);
268
269
module.exports = router;
270
271
// Product routes module (products.js)
272
const express = require('express');
273
const router = express.Router();
274
275
router.get('/', getAllProducts);
276
router.get('/:id', getProduct);
277
router.post('/', createProduct);
278
279
module.exports = router;
280
281
// Main application
282
const express = require('express');
283
const userRoutes = require('./routes/users');
284
const productRoutes = require('./routes/products');
285
286
const app = express();
287
288
// Mount routers
289
app.use('/api/users', userRoutes);
290
app.use('/api/products', productRoutes);
291
292
// Nested router mounting
293
const apiRouter = express.Router();
294
apiRouter.use('/users', userRoutes);
295
apiRouter.use('/products', productRoutes);
296
app.use('/api/v1', apiRouter);
297
```
298
299
### Route Path Patterns
300
301
Express routers support various path pattern syntaxes for flexible route matching.
302
303
**Path Pattern Examples:**
304
305
```javascript
306
// String patterns
307
router.get('/users', handler); // Exact match
308
router.get('/users/*', handler); // Wildcard
309
router.get('/files/*.*', handler); // File with extension
310
311
// String patterns with parameters
312
router.get('/users/:id', handler); // Single parameter
313
router.get('/users/:id/posts/:postId', handler); // Multiple parameters
314
router.get('/users/:id?', handler); // Optional parameter
315
316
// RegExp patterns
317
router.get(/.*fly$/, handler); // Ends with 'fly'
318
router.get(/users\/(\d+)/, handler); // Users with numeric ID
319
320
// Array of patterns
321
router.get(['/users', '/people'], handler); // Multiple exact matches
322
```
323
324
**Parameter Access:**
325
326
```javascript
327
router.get('/users/:userId/posts/:postId', (req, res) => {
328
const { userId, postId } = req.params;
329
console.log(`User: ${userId}, Post: ${postId}`);
330
res.json({ userId, postId });
331
});
332
333
// With optional parameters
334
router.get('/posts/:year/:month?', (req, res) => {
335
const { year, month } = req.params;
336
// month will be undefined if not provided
337
res.json({ year, month: month || 'all' });
338
});
339
```
340
341
### Error Handling in Routers
342
343
Handle errors within router middleware and route handlers.
344
345
```javascript { .api }
346
/**
347
* Error handling middleware signature
348
* @param {Error} err - Error object
349
* @param {Request} req - Request object
350
* @param {Response} res - Response object
351
* @param {NextFunction} next - Next function
352
*/
353
type ErrorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => void;
354
```
355
356
**Usage Examples:**
357
358
```javascript
359
const router = express.Router();
360
361
// Route with error handling
362
router.get('/users/:id', async (req, res, next) => {
363
try {
364
const user = await User.findById(req.params.id);
365
if (!user) {
366
const error = new Error('User not found');
367
error.status = 404;
368
return next(error);
369
}
370
res.json(user);
371
} catch (error) {
372
next(error); // Pass error to error handler
373
}
374
});
375
376
// Router-level error handler
377
router.use((err, req, res, next) => {
378
const status = err.status || 500;
379
res.status(status).json({
380
error: {
381
message: err.message,
382
status: status
383
}
384
});
385
});
386
```
387
388
### Router Properties
389
390
```javascript { .api }
391
/**
392
* Router parameter callbacks
393
*/
394
params: { [key: string]: Function[] };
395
396
/**
397
* Case sensitivity setting
398
*/
399
caseSensitive: boolean;
400
401
/**
402
* Merge parameters setting
403
*/
404
mergeParams: boolean;
405
406
/**
407
* Strict routing setting
408
*/
409
strict: boolean;
410
```
411
412
**Usage Examples:**
413
414
```javascript
415
const router = express.Router({ mergeParams: true });
416
417
// Check router configuration
418
console.log('Merge params:', router.mergeParams); // true
419
console.log('Case sensitive:', router.caseSensitive); // false (default)
420
console.log('Strict routing:', router.strict); // false (default)
421
```