Express style path to RegExp utility for URL routing and parameter extraction
npx @tessl/cli install tessl/npm-path-to-regexp@8.3.00
# Path-to-RegExp
1
2
Path-to-RegExp is a comprehensive TypeScript library that converts Express-style path strings (like `/user/:name`) into regular expressions for URL matching and parameter extraction. It provides a complete API for path parsing, matching, compilation, and transformation with full TypeScript support.
3
4
## Package Information
5
6
- **Package Name**: path-to-regexp
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install path-to-regexp`
10
11
## Core Imports
12
13
```typescript { .api }
14
// Main functions
15
import {
16
match,
17
pathToRegexp,
18
compile,
19
parse,
20
stringify
21
} from "path-to-regexp";
22
23
// Classes and errors
24
import { TokenData, PathError } from "path-to-regexp";
25
26
// Types (import as needed)
27
import type {
28
MatchFunction,
29
PathFunction,
30
MatchResult,
31
Match,
32
Key,
33
Keys,
34
Token,
35
Text,
36
Parameter,
37
Wildcard,
38
Group,
39
Encode,
40
Decode,
41
Path,
42
ParamData,
43
ParseOptions,
44
MatchOptions,
45
CompileOptions,
46
PathToRegexpOptions
47
} from "path-to-regexp";
48
```
49
50
For CommonJS:
51
52
```javascript
53
const {
54
match,
55
pathToRegexp,
56
compile,
57
parse,
58
stringify
59
} = require("path-to-regexp");
60
```
61
62
## Basic Usage
63
64
```typescript
65
import { match, compile, parse } from "path-to-regexp";
66
67
// Create a match function for URL testing
68
const matchUser = match("/users/:id");
69
const result = matchUser("/users/123");
70
// Result: { path: '/users/123', params: { id: '123' } }
71
72
// Create a path generator function
73
const generateUserPath = compile("/users/:id");
74
const userUrl = generateUserPath({ id: "456" });
75
// Result: "/users/456"
76
77
// Parse a path into tokens
78
const tokens = parse("/users/:id/posts/:postId");
79
// Result: TokenData with parsed parameter and text tokens
80
```
81
82
## Architecture
83
84
Path-to-RegExp is built around several key components:
85
86
- **Path Parsing**: Convert path strings into structured token representations
87
- **Pattern Matching**: Generate RegExp patterns and match functions for URL testing
88
- **Path Compilation**: Create template functions for reverse URL generation from parameters
89
- **Token Processing**: Internal system for handling parameters, wildcards, and optional segments
90
- **Type Safety**: Full TypeScript integration with generic parameter types
91
92
## Capabilities
93
94
### Path Parsing
95
96
Convert path strings into structured token data for analysis and processing.
97
98
```typescript { .api }
99
/**
100
* Parse a path string into tokenized data structure
101
* @param str - Path string to parse (e.g., "/users/:id")
102
* @param options - Parsing configuration (default: {})
103
* @returns TokenData instance containing parsed tokens
104
*/
105
function parse(str: string, options: ParseOptions = {}): TokenData;
106
107
interface ParseOptions {
108
/** Function for encoding input strings */
109
encodePath?: Encode;
110
}
111
112
class TokenData {
113
constructor(
114
public readonly tokens: Token[],
115
public readonly originalPath?: string
116
);
117
}
118
```
119
120
**Usage Examples:**
121
122
```typescript
123
import { parse } from "path-to-regexp";
124
125
// Parse a simple path with parameters
126
const simpleTokens = parse("/users/:id");
127
128
// Parse a path with optional segments
129
const optionalTokens = parse("/users{/:id}/posts");
130
131
// Parse a path with wildcards
132
const wildcardTokens = parse("/files/*path");
133
134
// Parse with custom encoding
135
const encodedTokens = parse("/files/:name", {
136
encodePath: (str) => encodeURIComponent(str)
137
});
138
```
139
140
### Path Matching
141
142
Create functions that test strings against path patterns and extract parameters.
143
144
```typescript { .api }
145
/**
146
* Transform a path into a match function for testing strings
147
* @param path - Path string, TokenData object, or array of paths
148
* @param options - Matching and parsing configuration (default: {})
149
* @returns Function that matches input strings and extracts parameters
150
*/
151
function match<P extends ParamData>(
152
path: Path | Path[],
153
options: MatchOptions & ParseOptions = {}
154
): MatchFunction<P>;
155
156
interface MatchOptions extends PathToRegexpOptions {
157
/** Function for decoding strings for params, or false to disable (default: decodeURIComponent) */
158
decode?: Decode | false;
159
}
160
161
interface PathToRegexpOptions {
162
/** Matches the path completely without trailing characters (default: true) */
163
end?: boolean;
164
/** Allows optional trailing delimiter to match (default: true) */
165
trailing?: boolean;
166
/** Match will be case sensitive (default: false) */
167
sensitive?: boolean;
168
/** The default delimiter for segments (default: '/') */
169
delimiter?: string;
170
}
171
172
type MatchFunction<P extends ParamData> = (path: string) => Match<P>;
173
type Match<P extends ParamData> = false | MatchResult<P>;
174
175
interface MatchResult<P extends ParamData> {
176
path: string;
177
params: P;
178
}
179
```
180
181
**Usage Examples:**
182
183
```typescript
184
import { match } from "path-to-regexp";
185
186
// Basic parameter matching
187
const matchUser = match("/users/:id");
188
const userResult = matchUser("/users/123");
189
// Result: { path: '/users/123', params: { id: '123' } }
190
191
// Multiple parameters
192
const matchPost = match("/users/:userId/posts/:postId");
193
const postResult = matchPost("/users/123/posts/456");
194
// Result: { path: '/users/123/posts/456', params: { userId: '123', postId: '456' } }
195
196
// Wildcard matching
197
const matchFiles = match("/files/*path");
198
const fileResult = matchFiles("/files/documents/report.pdf");
199
// Result: { path: '/files/documents/report.pdf', params: { path: ['documents', 'report.pdf'] } }
200
201
// Optional segments
202
const matchOptional = match("/users{/:id}/profile");
203
const optResult1 = matchOptional("/users/profile");
204
// Result: { path: '/users/profile', params: {} }
205
const optResult2 = matchOptional("/users/123/profile");
206
// Result: { path: '/users/123/profile', params: { id: '123' } }
207
208
// Case-sensitive matching
209
const matchCase = match("/Users/:id", { sensitive: true });
210
const caseResult = matchCase("/users/123"); // false (case mismatch)
211
212
// Custom decoding
213
const matchDecoded = match("/files/:name", {
214
decode: (value) => decodeURIComponent(value)
215
});
216
```
217
218
### Path Compilation
219
220
Create template functions that generate URLs from parameter data.
221
222
```typescript { .api }
223
/**
224
* Compile a path into a template function for reverse path generation
225
* @param path - Path string or TokenData object
226
* @param options - Compilation and parsing configuration (default: {})
227
* @returns Function that generates paths from parameter data
228
*/
229
function compile<P extends ParamData>(
230
path: Path,
231
options: CompileOptions & ParseOptions = {}
232
): PathFunction<P>;
233
234
interface CompileOptions {
235
/** Function for encoding input strings for output, or false to disable (default: encodeURIComponent) */
236
encode?: Encode | false;
237
/** The default delimiter for segments (default: '/') */
238
delimiter?: string;
239
}
240
241
type PathFunction<P extends ParamData> = (data?: P) => string;
242
```
243
244
**Usage Examples:**
245
246
```typescript
247
import { compile } from "path-to-regexp";
248
249
// Basic path generation
250
const generateUser = compile("/users/:id");
251
const userPath = generateUser({ id: "123" });
252
// Result: "/users/123"
253
254
// Multiple parameters
255
const generatePost = compile("/users/:userId/posts/:postId");
256
const postPath = generatePost({ userId: "123", postId: "456" });
257
// Result: "/users/123/posts/456"
258
259
// Wildcard paths
260
const generateFile = compile("/files/*path");
261
const filePath = generateFile({ path: ["documents", "report.pdf"] });
262
// Result: "/files/documents/report.pdf"
263
264
// Optional segments
265
const generateOptional = compile("/users{/:id}/profile");
266
const optPath1 = generateOptional({}); // "/users/profile"
267
const optPath2 = generateOptional({ id: "123" }); // "/users/123/profile"
268
269
// Custom encoding
270
const generateEncoded = compile("/files/:name", {
271
encode: (value) => encodeURIComponent(value).replace(/%20/g, '+')
272
});
273
const encodedPath = generateEncoded({ name: "my file.txt" });
274
// Result: "/files/my+file.txt"
275
```
276
277
### RegExp Generation
278
279
Generate regular expressions and capture keys for direct pattern matching.
280
281
```typescript { .api }
282
/**
283
* Convert path to RegExp and extract capture keys
284
* @param path - Path string, TokenData object, or array of paths
285
* @param options - Regex generation and parsing configuration (default: {})
286
* @returns Object with regexp (RegExp) and keys (Keys array)
287
*/
288
function pathToRegexp(
289
path: Path | Path[],
290
options: PathToRegexpOptions & ParseOptions = {}
291
): { regexp: RegExp; keys: Keys };
292
293
type Keys = Array<Key>;
294
type Key = Parameter | Wildcard;
295
```
296
297
**Usage Examples:**
298
299
```typescript
300
import { pathToRegexp } from "path-to-regexp";
301
302
// Generate RegExp for direct matching
303
const { regexp, keys } = pathToRegexp("/users/:id");
304
const match = regexp.exec("/users/123");
305
// match: ["/users/123", "123"]
306
// keys: [{ type: "param", name: "id" }]
307
308
// Multiple paths (alternative routes)
309
const { regexp: multiRegexp, keys: multiKeys } = pathToRegexp([
310
"/users/:id",
311
"/user/:id"
312
]);
313
314
// Case-sensitive RegExp
315
const { regexp: sensitiveRegexp } = pathToRegexp("/Users/:id", {
316
sensitive: true
317
});
318
319
// Non-ending RegExp (allows additional characters)
320
const { regexp: partialRegexp } = pathToRegexp("/api/:version", {
321
end: false
322
});
323
```
324
325
### Path Stringification
326
327
Convert tokenized path data back to path strings.
328
329
```typescript { .api }
330
/**
331
* Convert tokenized path data back to path string
332
* @param data - TokenData instance to stringify
333
* @returns Path string representation
334
*/
335
function stringify(data: TokenData): string;
336
```
337
338
**Usage Examples:**
339
340
```typescript
341
import { parse, stringify } from "path-to-regexp";
342
343
// Parse and stringify round-trip
344
const tokens = parse("/users/:id/posts/:postId");
345
const pathString = stringify(tokens);
346
// Result: "/users/:id/posts/:postId"
347
348
// Stringify complex paths
349
const complexTokens = parse("/users{/:id}/posts/*path");
350
const complexString = stringify(complexTokens);
351
// Result: "/users{/:id}/posts/*path"
352
```
353
354
## Types
355
356
### Core Types
357
358
```typescript { .api }
359
type Encode = (value: string) => string;
360
type Decode = (value: string) => string;
361
type Path = string | TokenData;
362
type ParamData = Partial<Record<string, string | string[]>>;
363
```
364
365
### Token Types
366
367
```typescript { .api }
368
type Token = Text | Parameter | Wildcard | Group;
369
370
interface Text {
371
type: "text";
372
value: string;
373
}
374
375
interface Parameter {
376
type: "param";
377
name: string;
378
}
379
380
interface Wildcard {
381
type: "wildcard";
382
name: string;
383
}
384
385
interface Group {
386
type: "group";
387
tokens: Token[];
388
}
389
```
390
391
### Error Handling
392
393
```typescript { .api }
394
class PathError extends TypeError {
395
constructor(
396
message: string,
397
public readonly originalPath: string | undefined
398
);
399
}
400
```
401
402
The `PathError` class is thrown when there are syntax errors in path strings, such as:
403
- Unterminated groups (`/users{/:id`)
404
- Missing parameter names (`/users/:`)
405
- Invalid parameter names (`/users/:123`)
406
- Unexpected tokens
407
408
**Usage Examples:**
409
410
```typescript
411
import { parse, match, compile, PathError } from "path-to-regexp";
412
413
// Parsing errors
414
try {
415
const tokens = parse("/users{/:id"); // Unterminated group
416
} catch (error) {
417
if (error instanceof PathError) {
418
console.log(error.message); // Includes helpful error info
419
console.log(error.originalPath); // "/users{/:id"
420
}
421
}
422
423
// Parameter validation in compile
424
try {
425
const generatePath = compile("/users/:id");
426
const path = generatePath({}); // Missing required parameter
427
} catch (error) {
428
console.log(error.message); // "Missing parameters: id"
429
}
430
431
// Type errors in wildcard parameters
432
try {
433
const generateWildcard = compile("/files/*path");
434
const path = generateWildcard({ path: "not-an-array" }); // Invalid type
435
} catch (error) {
436
console.log(error.message); // 'Expected "path" to be a non-empty array'
437
}
438
```
439
440
## Advanced Usage Patterns
441
442
### Multiple Path Alternatives
443
444
Match against multiple possible path patterns:
445
446
```typescript
447
import { match } from "path-to-regexp";
448
449
const matchMultiple = match([
450
"/users/:id",
451
"/user/:id",
452
"/u/:id"
453
]);
454
455
const result = matchMultiple("/u/123");
456
// Result: { path: '/u/123', params: { id: '123' } }
457
```
458
459
### Custom Parameter Processing
460
461
```typescript
462
import { match, compile } from "path-to-regexp";
463
464
// Custom decoding for match
465
const matchCustom = match("/files/:name", {
466
decode: (value) => {
467
// Custom decoding logic
468
return decodeURIComponent(value).replace(/\+/g, ' ');
469
}
470
});
471
472
// Custom encoding for compile
473
const compileCustom = compile("/files/:name", {
474
encode: (value) => {
475
// Custom encoding logic
476
return encodeURIComponent(value).replace(/%20/g, '+');
477
}
478
});
479
```
480
481
### TypeScript Generic Usage
482
483
```typescript
484
import { match, compile, type MatchResult } from "path-to-regexp";
485
486
// Type-safe parameter interfaces
487
interface UserParams {
488
id: string;
489
}
490
491
interface PostParams {
492
userId: string;
493
postId: string;
494
}
495
496
const matchUser = match<UserParams>("/users/:id");
497
const matchPost = match<PostParams>("/users/:userId/posts/:postId");
498
499
const compileUser = compile<UserParams>("/users/:id");
500
const compilePost = compile<PostParams>("/users/:userId/posts/:postId");
501
502
// Type-safe usage
503
const userResult = matchUser("/users/123"); // MatchResult<UserParams> | false
504
if (userResult) {
505
console.log(userResult.params.id); // TypeScript knows this is string
506
}
507
```