Registry / serialization / path-to-regexp

path-to-regexp

JSON →
library8.4.2jsnpmunverified

path-to-regexp is a robust JavaScript/TypeScript utility for converting Express-style path strings, such as `/user/:name`, into regular expressions. It is widely used in routing libraries to match URLs against defined patterns, supporting features like named parameters (`:foo`), wildcards (`*splat`), and optional segments (`{/:id}`). The library also provides reverse functionality through its `compile` and `stringify` methods, allowing parameters to be transformed back into path strings. Currently at version `8.4.2`, it maintains an active development cadence with regular updates focusing on performance enhancements, bundle size reduction, and critical security fixes. Its primary differentiator is its comprehensive feature set for complex path matching and generation, making it a foundational component for many web frameworks and routers. It explicitly states its purpose for ordered data like paths, not arbitrary data like query strings. This package ships with TypeScript types.

npm install path-to-regexp
INSTALL
IMPORT
SIG · PATH-TO-REGEXP
P
path-to-regexp
serializationjavascriptv8.4.2
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

match
✓ import { match } from 'path-to-regexp'
✗ import PathToRegexp from 'path-to-regexp'
Use named imports for ESM. The default export is not the primary API.
pathToRegexp
✓ import { pathToRegexp } from 'path-to-regexp'
✗ const pathToRegexp = require('path-to-regexp')
`pathToRegexp` was re-added in v8.1.0; prefer named imports over CommonJS `require` for modern TypeScript/ESM projects.
compile
✓ import { compile } from 'path-to-regexp'
✗ import * as PathToRegexp from 'path-to-regexp'; PathToRegexp.compile(...);
Destructure specific functions from the module for clarity.

Demonstrates path matching with parameters, wildcards, and optional segments, along with reverse path compilation and direct RegExp generation.

import { match, compile, pathToRegexp } from 'path-to-regexp'; // 1. Basic Parameter Matching const userMatcher = match<{ id: string }>('/user/:id'); const userMatchResult = userMatcher('/user/123'); console.log('User Match:', userMatchResult); // e.g., { path: '/user/123', params: { id: '123' } } // 2. Wildcard Matching const splatMatcher = match<{ splat: string[] }>('/*splat'); const splatMatchResult = splatMatcher('/foo/bar/baz'); console.log('Splat Match:', splatMatchResult); // e.g., { path: '/foo/bar/baz', params: { splat: ['foo', 'bar', 'baz'] } } // 3. Optional Segments const optionalMatcher = match<{ id?: string }>('/items{/:id}'); const optionalMatchResult1 = optionalMatcher('/items'); const optionalMatchResult2 = optionalMatcher('/items/456'); console.log('Optional Match (no ID):', optionalMatchResult1); // e.g., { path: '/items', params: {} } console.log('Optional Match (with ID):', optionalMatchResult2); // e.g., { path: '/items/456', params: { id: '456' } } // 4. Compiling/Reverse Routing const toUserPath = compile<{ id: string }>('/profile/:id'); const compiledPath = toUserPath({ id: 'john-doe' }); console.log('Compiled Path:', compiledPath); // e.g., '/profile/john-doe' // 5. Raw RegExp generation const { regexp, keys } = pathToRegexp('/data/:category/:item'); console.log('RegExp:', regexp); // e.g., /^\/data\/(?:([^\/]+?))\/(?:([^\/]+?))\/?$/i console.log('Keys:', keys); // e.g., [{ name: 'category', ... }, { name: 'item', ... }] const execResult = regexp.exec('/data/electronics/laptop'); if (execResult) { const params: { [key: string]: string } = {}; keys.forEach((key, i) => { params[key.name] = execResult[i + 1]; }); console.log('RegExp Exec Params:', params); } // e.g., RegExp Exec Params: { category: 'electronics', item: 'laptop' }
Debug
Known issues
breakingMultiple critical security vulnerabilities (CVE-2026-4926, CVE-2026-4923, CVE-2026-4867) have been identified and patched. These could lead to denial-of-service or unexpected path resolution. Immediate upgrade is strongly advised.
fix
Upgrade to `path-to-regexp@8.4.0` (or higher) for the 8.x branch, or `path-to-regexp@0.1.13` (or higher) for the 0.1.x branch.
affects: <8.4.0 || <0.1.13
breakingVarious backtracking protection fixes across major versions (8.x, 6.x, 0.1.x) have altered how complex paths, wildcards, and optional segments are matched. For instance, `v8.4.1` removed trie deduplication, which fixed wildcard regressions but might change matching behavior for some existing paths.
fix
Review your routing patterns carefully after upgrading, especially those using complex wildcards (`*splat`) or nested optional groups, as previously valid paths might now resolve differently or no longer match.
affects: >=6.3.0, >=0.1.12, >=8.4.0
gotchaThe `pathToRegexp` method was explicitly re-added in `v8.1.0`. If you are using an older version where it might have been temporarily removed or if your codebase depends on specific behaviors from previous major versions, ensure its availability and expected functionality.
fix
Ensure you are on `v8.1.0` or later to use `pathToRegexp` directly, or adjust your code to use `match().regexp` for the generated regular expression.
affects: <8.1.0
gotchaAs of `v8.2.0`, the library targets ES2015, removing private class fields and the `s` (dotAll) flag from generated regular expressions. This change primarily improves browser compatibility and bundle size but could subtly affect very specific regex patterns or compatibility with extremely outdated JavaScript environments.
fix
No direct fix required for most users; be aware of potential subtle regex behavior changes if relying on the `s` flag or targeting pre-ES2015 environments.
affects: >=8.2.0
Errors
Common errors & fixes
TypeError: pathToRegexp is not a function
Attempting to use `pathToRegexp` in a version prior to `v8.1.0` where it might have been removed or trying to access it via an incorrect import/require method.
fix
Upgrade to `path-to-regexp@8.1.0` or newer. Ensure you are using `import { pathToRegexp } from 'path-to-regexp'` in ESM or `const { pathToRegexp } = require('path-to-regexp')` in CommonJS.
Unexpected path matching for wildcards or optional segments (e.g., `/*foo` matches `/a` instead of `/a/b`)
Related to backtracking fixes and the removal of trie deduplication in `v8.4.1` and other versions, which altered how complex patterns are resolved.
fix
Carefully test your routing patterns with the latest version. If encountering issues, simplify your path patterns or consult the changelog for specific behavior changes related to wildcards and backtracking in `v8.4.1` and `v8.4.0`.
Path does not match as expected (e.g., trailing slash issues, case sensitivity)
Incorrect `options` passed to `match` or `pathToRegexp`, such as `sensitive`, `end`, or `trailing`.
fix
Explicitly set `sensitive: true` for case-sensitive matching, `end: false` if the path doesn't need to match until the end of the string, or `trailing: false` to disallow optional trailing delimiters. E.g., `match('/foo', { end: false })`.
RangeError: Maximum call stack size exceeded
Extremely complex path definitions or specific regular expression engines could hit recursion limits, especially in older versions before backtracking improvements.
fix
Simplify complex path definitions where possible. Ensure you are on the latest `path-to-regexp` version, as many backtracking-related performance and stability issues have been addressed.
Upgrade
Version history
8.4.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
6 hits · last 30 days
node
6
Resources
path-to-regexp — npm install path-to-regexp · libregistry