{"id":13750,"library":"path-to-regexp","title":"Express-style Path to RegExp Utility","description":"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.","status":"active","version":"8.4.2","language":"javascript","source_language":"en","source_url":"https://github.com/pillarjs/path-to-regexp","tags":["javascript","express","regexp","route","routing","typescript"],"install":[{"cmd":"npm install path-to-regexp","lang":"bash","label":"npm"},{"cmd":"yarn add path-to-regexp","lang":"bash","label":"yarn"},{"cmd":"pnpm add path-to-regexp","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Use named imports for ESM. The default export is not the primary API.","wrong":"import PathToRegexp from 'path-to-regexp'","symbol":"match","correct":"import { match } from 'path-to-regexp'"},{"note":"`pathToRegexp` was re-added in v8.1.0; prefer named imports over CommonJS `require` for modern TypeScript/ESM projects.","wrong":"const pathToRegexp = require('path-to-regexp')","symbol":"pathToRegexp","correct":"import { pathToRegexp } from 'path-to-regexp'"},{"note":"Destructure specific functions from the module for clarity.","wrong":"import * as PathToRegexp from 'path-to-regexp'; PathToRegexp.compile(...);","symbol":"compile","correct":"import { compile } from 'path-to-regexp'"}],"quickstart":{"code":"import { match, compile, pathToRegexp } from 'path-to-regexp';\n\n// 1. Basic Parameter Matching\nconst userMatcher = match<{ id: string }>('/user/:id');\nconst userMatchResult = userMatcher('/user/123');\nconsole.log('User Match:', userMatchResult); // e.g., { path: '/user/123', params: { id: '123' } }\n\n// 2. Wildcard Matching\nconst splatMatcher = match<{ splat: string[] }>('/*splat');\nconst splatMatchResult = splatMatcher('/foo/bar/baz');\nconsole.log('Splat Match:', splatMatchResult); // e.g., { path: '/foo/bar/baz', params: { splat: ['foo', 'bar', 'baz'] } }\n\n// 3. Optional Segments\nconst optionalMatcher = match<{ id?: string }>('/items{/:id}');\nconst optionalMatchResult1 = optionalMatcher('/items');\nconst optionalMatchResult2 = optionalMatcher('/items/456');\nconsole.log('Optional Match (no ID):', optionalMatchResult1); // e.g., { path: '/items', params: {} }\nconsole.log('Optional Match (with ID):', optionalMatchResult2); // e.g., { path: '/items/456', params: { id: '456' } }\n\n// 4. Compiling/Reverse Routing\nconst toUserPath = compile<{ id: string }>('/profile/:id');\nconst compiledPath = toUserPath({ id: 'john-doe' });\nconsole.log('Compiled Path:', compiledPath); // e.g., '/profile/john-doe'\n\n// 5. Raw RegExp generation\nconst { regexp, keys } = pathToRegexp('/data/:category/:item');\nconsole.log('RegExp:', regexp); // e.g., /^\\/data\\/(?:([^\\/]+?))\\/(?:([^\\/]+?))\\/?$/i\nconsole.log('Keys:', keys);     // e.g., [{ name: 'category', ... }, { name: 'item', ... }]\nconst execResult = regexp.exec('/data/electronics/laptop');\nif (execResult) {\n  const params: { [key: string]: string } = {};\n  keys.forEach((key, i) => {\n    params[key.name] = execResult[i + 1];\n  });\n  console.log('RegExp Exec Params:', params);\n} // e.g., RegExp Exec Params: { category: 'electronics', item: 'laptop' }","lang":"typescript","description":"Demonstrates path matching with parameters, wildcards, and optional segments, along with reverse path compilation and direct RegExp generation."},"warnings":[{"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.","message":"Multiple 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.","severity":"breaking","affected_versions":"<8.4.0 || <0.1.13"},{"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.","message":"Various 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.","severity":"breaking","affected_versions":">=6.3.0, >=0.1.12, >=8.4.0"},{"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.","message":"The `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.","severity":"gotcha","affected_versions":"<8.1.0"},{"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.","message":"As 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.","severity":"gotcha","affected_versions":">=8.2.0"}],"env_vars":null,"search_vec":"'/user':26 '8.4.2':80 'activ':84 'allow':68 'also':58 'arbitrari':137 'back':73 'bundl':94 'cadenc':86 'compil':64 'complex':110 'compon':119 'comprehens':106 'convert':18 'critic':98 'current':77 'data':133,138 'defin':42 'develop':85 'differenti':103 'enhanc':93 'explicit':127 'express':2,20,30,149 'express-styl':1,19 'featur':45,107 'fix':100 'focus':90 'foo':49 'foundat':118 'framework':123 'function':61 'generat':114 'id':55 'javascript':148 'javascript/typescript':15 'librari':37,57 'like':46,134,139 'maintain':82 'make':115 'mani':121 'match':39,112 'method':67 'name':27,47 'option':53 'order':132 'packag':143 'paramet':48,69 'path':4,9,22,75,111,135 'path-to-regexp':8 'pattern':43 'perform':92 'primari':102 'provid':59 'purpos':130 'queri':140 'reduct':96 'regexp':6,11,150 'regular':29,88 'revers':60 'robust':14 'rout':36,151,152 'router':125 'secur':99 'segment':54 'set':108 'ship':144 'size':95 'splat':51 'state':128 'string':23,76,141 'stringifi':66 'style':3,21 'support':44 'transform':72 'type':147 'typescript':146,153 'updat':89 'url':40 'use':34 'util':7,16 'version':79 'web':122 'wide':33 'wildcard':50","created_at":"2026-04-20T01:56:07.334869+00:00","updated_at":"2026-04-20T01:56:07.334869+00:00","problems":[{"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.","cause":"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.","error":"TypeError: pathToRegexp is not a function"},{"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`.","cause":"Related to backtracking fixes and the removal of trie deduplication in `v8.4.1` and other versions, which altered how complex patterns are resolved.","error":"Unexpected path matching for wildcards or optional segments (e.g., `/*foo` matches `/a` instead of `/a/b`)"},{"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 })`.","cause":"Incorrect `options` passed to `match` or `pathToRegexp`, such as `sensitive`, `end`, or `trailing`.","error":"Path does not match as expected (e.g., trailing slash issues, case sensitivity)"},{"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.","cause":"Extremely complex path definitions or specific regular expression engines could hit recursion limits, especially in older versions before backtracking improvements.","error":"RangeError: Maximum call stack size exceeded"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/pillarjs/path-to-regexp","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/path-to-regexp","openapi_spec":null,"status_page":null,"smithery":null,"categories":["serialization","http-networking"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}