0
# Koa Route
1
2
Koa Route is an uber simple route middleware for Koa.js applications. It provides minimalist routing functionality with path parameter support and pattern matching, focusing on simplicity and performance without the overhead of complex routing features.
3
4
## Package Information
5
6
- **Package Name**: koa-route
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install koa-route`
10
11
## Core Imports
12
13
```javascript
14
const route = require('koa-route');
15
```
16
17
For ES6 modules:
18
19
```javascript
20
import * as route from 'koa-route';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const Koa = require('koa');
27
const route = require('koa-route');
28
const app = new Koa();
29
30
// Simple route with no parameters
31
app.use(route.get('/users', (ctx) => {
32
ctx.body = 'All users';
33
}));
34
35
// Route with path parameter
36
app.use(route.get('/users/:id', (ctx, id) => {
37
ctx.body = `User ${id}`;
38
}));
39
40
// Route supporting all HTTP methods
41
app.use(route.all('/api/:resource', (ctx, resource) => {
42
ctx.body = `${ctx.method} request for ${resource}`;
43
}));
44
45
app.listen(3000);
46
```
47
48
## Architecture
49
50
Koa Route provides a lightweight routing system built around:
51
52
- **Method-specific Route Creators**: Individual functions for each HTTP method (get, post, put, etc.)
53
- **Universal Route Creator**: `all()` method that matches any HTTP method
54
- **Path Pattern Matching**: Powered by path-to-regexp for parameter extraction and pattern matching
55
- **Middleware Generation**: Each route function returns standard Koa middleware
56
- **Context Enhancement**: Adds `routePath` property to Koa context for matched routes
57
58
## Capabilities
59
60
### HTTP Method Routing
61
62
Route creators for all standard HTTP methods, each generating middleware that matches specific HTTP methods and URL patterns.
63
64
```javascript { .api }
65
/**
66
* Create route middleware for GET requests
67
* @param {string} path - URL pattern with optional parameters (uses path-to-regexp syntax)
68
* @param {Function} [handler] - Route handler function with signature (ctx, ...params, next)
69
* @param {Object} [options] - Options passed to path-to-regexp
70
* @returns {Function} Koa middleware function or route creator function
71
*/
72
function get(path, handler, options);
73
74
/**
75
* Create route middleware for POST requests
76
* @param {string} path - URL pattern with optional parameters
77
* @param {Function} [handler] - Route handler function
78
* @param {Object} [options] - Options for path-to-regexp
79
* @returns {Function} Koa middleware function or route creator function
80
*/
81
function post(path, handler, options);
82
83
/**
84
* Create route middleware for PUT requests
85
* @param {string} path - URL pattern with optional parameters
86
* @param {Function} [handler] - Route handler function
87
* @param {Object} [options] - Options for path-to-regexp
88
* @returns {Function} Koa middleware function or route creator function
89
*/
90
function put(path, handler, options);
91
92
/**
93
* Create route middleware for PATCH requests
94
* @param {string} path - URL pattern with optional parameters
95
* @param {Function} [handler] - Route handler function
96
* @param {Object} [options] - Options for path-to-regexp
97
* @returns {Function} Koa middleware function or route creator function
98
*/
99
function patch(path, handler, options);
100
101
/**
102
* Create route middleware for DELETE requests
103
* @param {string} path - URL pattern with optional parameters
104
* @param {Function} [handler] - Route handler function
105
* @param {Object} [options] - Options for path-to-regexp
106
* @returns {Function} Koa middleware function or route creator function
107
*/
108
function delete(path, handler, options);
109
110
/**
111
* Alias for delete method (since 'delete' is a reserved keyword)
112
* Same function as delete(), provided for convenience
113
*/
114
const del = delete;
115
116
/**
117
* Create route middleware for HEAD requests
118
* @param {string} path - URL pattern with optional parameters
119
* @param {Function} [handler] - Route handler function
120
* @param {Object} [options] - Options for path-to-regexp
121
* @returns {Function} Koa middleware function or route creator function
122
*/
123
function head(path, handler, options);
124
125
/**
126
* Create route middleware for OPTIONS requests
127
* @param {string} path - URL pattern with optional parameters
128
* @param {Function} [handler] - Route handler function
129
* @param {Object} [options] - Options for path-to-regexp
130
* @returns {Function} Koa middleware function or route creator function
131
*/
132
function options(path, handler, options);
133
134
// All HTTP methods from the 'methods' npm package are dynamically exported.
135
// Complete list of available methods:
136
function acl(path, handler, options);
137
function bind(path, handler, options);
138
function checkout(path, handler, options);
139
function connect(path, handler, options);
140
function copy(path, handler, options);
141
function link(path, handler, options);
142
function lock(path, handler, options);
143
function merge(path, handler, options);
144
function mkactivity(path, handler, options);
145
function mkcalendar(path, handler, options);
146
function mkcol(path, handler, options);
147
function move(path, handler, options);
148
function notify(path, handler, options);
149
function propfind(path, handler, options);
150
function proppatch(path, handler, options);
151
function purge(path, handler, options);
152
function rebind(path, handler, options);
153
function report(path, handler, options);
154
function search(path, handler, options);
155
function source(path, handler, options);
156
function subscribe(path, handler, options);
157
function trace(path, handler, options);
158
function unbind(path, handler, options);
159
function unlink(path, handler, options);
160
function unlock(path, handler, options);
161
function unsubscribe(path, handler, options);
162
```
163
164
**Usage Examples:**
165
166
```javascript
167
const route = require('koa-route');
168
169
// Direct handler assignment
170
app.use(route.get('/posts', (ctx) => {
171
ctx.body = 'All posts';
172
}));
173
174
// Route with parameters
175
app.use(route.post('/posts/:id', (ctx, id) => {
176
ctx.body = `Created post ${id}`;
177
}));
178
179
// Complex parameter patterns
180
app.use(route.get('/users/:id(\\\\d+)', (ctx, id) => {
181
ctx.body = `User with numeric ID: ${id}`;
182
}));
183
184
// Optional parameters
185
app.use(route.get('/api/:resource/:id?', (ctx, resource, id) => {
186
if (id) {
187
ctx.body = `${resource} item ${id}`;
188
} else {
189
ctx.body = `All ${resource}`;
190
}
191
}));
192
```
193
194
### Universal Method Routing
195
196
Route creator that matches all HTTP methods for a given path pattern.
197
198
```javascript { .api }
199
/**
200
* Create route middleware that matches all HTTP methods
201
* @param {string} path - URL pattern with optional parameters (uses path-to-regexp syntax)
202
* @param {Function} [handler] - Route handler function with signature (ctx, ...params, next)
203
* @param {Object} [options] - Options passed to path-to-regexp
204
* @returns {Function} Koa middleware function or route creator function
205
*/
206
function all(path, handler, options);
207
```
208
209
**Usage Examples:**
210
211
```javascript
212
// Match all methods for API endpoint
213
app.use(route.all('/api/:resource', (ctx, resource) => {
214
ctx.body = `${ctx.method} request for ${resource}`;
215
}));
216
217
// Composed route creation
218
const apiRoute = route.all('/api/:action');
219
app.use(apiRoute((ctx, action) => {
220
ctx.body = `API action: ${action}`;
221
}));
222
```
223
224
### Composed Route Creation
225
226
All route functions support composed creation where the handler is provided separately from the path pattern.
227
228
```javascript { .api }
229
/**
230
* Route creator function returned when handler is omitted
231
* @param {Function} handler - Route handler function with signature (ctx, ...params, next)
232
* @returns {Function} Koa middleware function
233
*/
234
function routeCreator(handler);
235
```
236
237
**Usage Examples:**
238
239
```javascript
240
// Create reusable route patterns
241
const userRoute = route.get('/users/:id');
242
const postRoute = route.get('/posts/:id');
243
244
// Apply different handlers to same pattern
245
app.use(userRoute((ctx, id) => {
246
ctx.body = `User ${id}`;
247
}));
248
249
app.use(postRoute((ctx, id) => {
250
ctx.body = `Post ${id}`;
251
}));
252
```
253
254
## Types
255
256
### Route Handler Function
257
258
```javascript { .api }
259
/**
260
* Route handler function signature
261
* @param {Object} ctx - Koa context object with added routePath property
262
* @param {...string} routeParams - Decoded URL parameters extracted from route pattern
263
* @param {Function} next - Koa next function for middleware chaining
264
* @returns {Promise|void} Promise that resolves when handler completes, or void for synchronous handlers
265
*/
266
function routeHandler(ctx, ...routeParams, next);
267
```
268
269
### Enhanced Koa Context
270
271
When a route matches, koa-route enhances the Koa context with additional properties:
272
273
```javascript { .api }
274
/**
275
* Enhanced Koa context with route information
276
*/
277
interface EnhancedContext extends KoaContext {
278
/** The original route pattern that matched the request */
279
routePath: string;
280
}
281
```
282
283
### Path-to-Regexp Options
284
285
Options object passed to the underlying path-to-regexp library for advanced pattern matching:
286
287
```javascript { .api }
288
/**
289
* Options for path-to-regexp pattern matching
290
*/
291
interface PathToRegexpOptions {
292
/** When true, the regexp allows an optional trailing delimiter to match */
293
strict?: boolean;
294
/** When true, the regexp will not match trailing delimiter */
295
end?: boolean;
296
/** When true, the regexp will be case sensitive */
297
sensitive?: boolean;
298
}
299
```
300
301
## Advanced Usage
302
303
### Method Matching Behavior
304
305
- **GET routes automatically handle HEAD requests**: HEAD requests to GET routes return the same response with an empty body
306
- **All other methods require exact matching**: POST, PUT, DELETE, etc. only match their specific method
307
- **Universal matching with `all()`**: The `all()` method matches any HTTP method
308
309
### Parameter Decoding
310
311
Route parameters are automatically URL-decoded using `decodeURIComponent()`:
312
313
```javascript
314
// URL: /package/http%3A%2F%2Fgithub.com
315
app.use(route.get('/package/:name', (ctx, name) => {
316
// name === 'http://github.com' (automatically decoded)
317
ctx.body = `Package: ${name}`;
318
}));
319
```
320
321
### Path Pattern Features
322
323
Supports all path-to-regexp pattern features:
324
325
- **Static paths**: `/users`
326
- **Named parameters**: `/users/:id`
327
- **Optional parameters**: `/users/:id?`
328
- **Custom regex patterns**: `/users/:id(\\\\d+)`
329
- **Multiple parameters**: `/users/:userId/posts/:postId`
330
331
### Error Handling
332
333
When routes don't match:
334
- The middleware calls `next()` to continue to the next middleware
335
- No automatic error responses are generated
336
- 404 handling should be implemented at the application level