Installations
npm install path-to-regexp
Score
99.8
Supply Chain
99.5
Quality
89.7
Maintenance
100
Vulnerability
100
License
Releases
8.2.0
Published on 26 Sept 2024
Error on bad input
Published on 12 Sept 2024
Fix backtracking in 6.x
Published on 12 Sept 2024
Add backtracking protection
Published on 10 Sept 2024
Fix backtracking in 1.x
Published on 10 Sept 2024
Support array inputs (again)
Published on 10 Sept 2024
Contributors
Developer
pillarjs
Module System
CommonJS, ESM
Statistics
8,200 Stars
342 Commits
384 Forks
65 Watching
6 Branches
51 Contributors
Updated on 19 Nov 2024
Bundle Size
5.00 kB
Minified
2.09 kB
Minified + Gzipped
Languages
TypeScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
10,223,044,175
Last day
5.4%
12,480,090
Compared to previous day
Last week
4%
63,753,657
Compared to previous week
Last month
13.3%
265,046,041
Compared to previous month
Last year
11.8%
2,605,335,753
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Path-to-RegExp
Turn a path string such as
/user/:name
into a regular expression.
Installation
npm install path-to-regexp --save
Usage
1const { 2 match, 3 pathToRegexp, 4 compile, 5 parse, 6 stringify, 7} = require("path-to-regexp");
Parameters
Parameters match arbitrary strings in a path by matching up to the end of the segment, or up to any proceeding tokens. They are defined by prefixing a colon to the parameter name (:foo
). Parameter names can use any valid JavaScript identifier, or be double quoted to use other characters (:"param-name"
).
1const fn = match("/:foo/:bar"); 2 3fn("/test/route"); 4//=> { path: '/test/route', params: { foo: 'test', bar: 'route' } }
Wildcard
Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (*foo
).
1const fn = match("/*splat"); 2 3fn("/bar/baz"); 4//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } }
Optional
Braces can be used to define parts of the path that are optional.
1const fn = match("/users{/:id}/delete"); 2 3fn("/users/delete"); 4//=> { path: '/users/delete', params: {} } 5 6fn("/users/123/delete"); 7//=> { path: '/users/123/delete', params: { id: '123' } }
Match
The match
function returns a function for matching strings against a path:
- path String or array of strings.
- options (optional) (Extends pathToRegexp options)
- decode Function for decoding strings to params, or
false
to disable all processing. (default:decodeURIComponent
)
- decode Function for decoding strings to params, or
1const fn = match("/foo/:bar");
Please note: path-to-regexp
is intended for ordered data (e.g. paths, hosts). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc).
PathToRegexp
The pathToRegexp
function returns a regular expression for matching strings against paths. It
- path String or array of strings.
- options (optional) (See parse for more options)
- sensitive Regexp will be case sensitive. (default:
false
) - end Validate the match reaches the end of the string. (default:
true
) - delimiter The default delimiter for segments, e.g.
[^/]
for:named
parameters. (default:'/'
) - trailing Allows optional trailing delimiter to match. (default:
true
)
- sensitive Regexp will be case sensitive. (default:
1const { regexp, keys } = pathToRegexp("/foo/:bar");
Compile ("Reverse" Path-To-RegExp)
The compile
function will return a function for transforming parameters into a valid path:
- path A string.
- options (See parse for more options)
- delimiter The default delimiter for segments, e.g.
[^/]
for:named
parameters. (default:'/'
) - encode Function for encoding input strings for output into the path, or
false
to disable entirely. (default:encodeURIComponent
)
- delimiter The default delimiter for segments, e.g.
1const toPath = compile("/user/:id"); 2 3toPath({ id: "name" }); //=> "/user/name" 4toPath({ id: "café" }); //=> "/user/caf%C3%A9" 5 6const toPathRepeated = compile("/*segment"); 7 8toPathRepeated({ segment: ["foo"] }); //=> "/foo" 9toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c" 10 11// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted. 12const toPathRaw = compile("/user/:id", { encode: false }); 13 14toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"
Stringify
Transform TokenData
(a sequence of tokens) back into a Path-to-RegExp string.
- data A
TokenData
instance
1const data = new TokenData([ 2 { type: "text", value: "/" }, 3 { type: "param", name: "foo" }, 4]); 5 6const path = stringify(data); //=> "/:foo"
Developers
- If you are rewriting paths with match and compile, consider using
encode: false
anddecode: false
to keep raw paths passed around. - To ensure matches work on paths containing characters usually encoded, such as emoji, consider using encodeurl for
encodePath
.
Parse
The parse
function accepts a string and returns TokenData
, the set of tokens and other metadata parsed from the input string. TokenData
is can used with match
and compile
.
- path A string.
- options (optional)
- encodePath A function for encoding input strings. (default:
x => x
, recommended:encodeurl
)
- encodePath A function for encoding input strings. (default:
Tokens
TokenData
is a sequence of tokens, currently of types text
, parameter
, wildcard
, or group
.
Custom path
In some applications, you may not be able to use the path-to-regexp
syntax, but still want to use this library for match
and compile
. For example:
1import { TokenData, match } from "path-to-regexp"; 2 3const tokens = [ 4 { type: "text", value: "/" }, 5 { type: "parameter", name: "foo" }, 6]; 7const path = new TokenData(tokens); 8const fn = match(path); 9 10fn("/test"); //=> { path: '/test', index: 0, params: { foo: 'test' } }
Errors
An effort has been made to ensure ambiguous paths from previous releases throw an error. This means you might be seeing an error when things worked before.
Unexpected ?
or +
In past releases, ?
, *
, and +
were used to denote optional or repeating parameters. As an alternative, try these:
- For optional (
?
), use an empty segment in a group such as/:file{.:ext}
. - For repeating (
+
), only wildcard matching is supported, such as/*path
. - For optional repeating (
*
), use a group and a wildcard parameter such as/files{/*path}
.
Unexpected (
, )
, [
, ]
, etc.
Previous versions of Path-to-RegExp used these for RegExp features. This version no longer supports them so they've been reserved to avoid ambiguity. To use these characters literally, escape them with a backslash, e.g. "\\("
.
Missing parameter name
Parameter names must be provided after :
or *
, and they must be a valid JavaScript identifier. If you want an parameter name that isn't a JavaScript identifier, such as starting with a number, you can wrap the name in quotes like :"my-name"
.
Unterminated quote
Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character.
Express <= 4.x
Path-To-RegExp breaks compatibility with Express <= 4.x
in the following ways:
- The wildcard
*
must have a name, matching the behavior of parameters:
. - The optional character
?
is no longer supported, use braces instead:/:file{.:ext}
. - Regexp characters are not supported.
- Some characters have been reserved to avoid confusion during upgrade (
()[]?+!
). - Parameter names now support valid JavaScript identifiers, or quoted like
:"this"
.
License
MIT
Stable Version
The latest stable version of the package.
Stable Version
8.2.0
HIGH
5
7.5/10
Summary
path-to-regexp outputs backtracking regular expressions
Affected Versions
>= 4.0.0, < 6.3.0
Patched Versions
6.3.0
7.5/10
Summary
path-to-regexp outputs backtracking regular expressions
Affected Versions
>= 7.0.0, < 8.0.0
Patched Versions
8.0.0
7.5/10
Summary
path-to-regexp outputs backtracking regular expressions
Affected Versions
>= 2.0.0, < 3.3.0
Patched Versions
3.3.0
7.5/10
Summary
path-to-regexp outputs backtracking regular expressions
Affected Versions
>= 0.2.0, < 1.9.0
Patched Versions
1.9.0
7.5/10
Summary
path-to-regexp outputs backtracking regular expressions
Affected Versions
< 0.1.10
Patched Versions
0.1.10
Reason
no binaries found in the repo
Reason
2 out of 2 merged PRs checked by a CI test -- score normalized to 10
Reason
27 different organizations found -- score normalized to 10
Details
- Info: contributors work for DefinitelyTyped,Thinkful-Ed,TypeStrong,alm-tools,apex,borderless,clibs,cojs,component,expressjs,github-beta,gohttp,hackreactor,jshttp,jstrace,koajs,nanodb,pillarjs,reworkcss,senchalabs,serviejs,slate,standardschema,typed-typings,typings,visionmedia,zeromq
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: License file found in expected location: LICENSE:1
- Info: FSF or OSI recognized license: LICENSE:1
Reason
17 commit(s) out of 30 and 23 issue activity out of 30 found in the last 90 days -- score normalized to 10
Reason
security policy file detected
Details
- Info: security policy file detected: SECURITY.md:1
- Info: Found linked content: SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: SECURITY.md:1
- Info: Found text in security policy: SECURITY.md:1
Reason
GitHub workflow tokens follow principle of least privilege
Details
- Info: topLevel 'contents' permission set to 'read': .github/workflows/ci.yml:6
- Info: topLevel 'contents' permission set to 'read': .github/workflows/scorecard.yml:20
- Info: no jobLevel write permissions found
Reason
1 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
Reason
dependency not pinned by hash detected -- score normalized to 6
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/pillarjs/path-to-regexp/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/pillarjs/path-to-regexp/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/pillarjs/path-to-regexp/ci.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:29: update your workflow using https://app.stepsecurity.io/secureworkflow/pillarjs/path-to-regexp/ci.yml/master?enable=pin
- Info: 3 out of 6 GitHub-owned GitHubAction dependencies pinned
- Info: 1 out of 2 third-party GitHubAction dependencies pinned
- Info: 1 out of 1 npmCommand dependencies pinned
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
found 28 unreviewed changesets out of 30 -- score normalized to 0
Reason
no update tool detected
Details
- Warn: tool 'RenovateBot' is not used: Follow the instructions from https://docs.renovatebot.com/configuration-options/. (Low effort)
- Warn: tool 'Dependabot' is not used: Follow the instructions from https://docs.github.com/code-security/dependabot/dependabot-version-updates/about-dependabot-version-updates. (Low effort)
- Warn: tool 'PyUp' is not used: Follow the instructions from https://docs.pyup.io/docs. (Low effort)
- Warn: tool 'Sonatype Lift' is not used: Follow the instructions from https://help.sonatype.com/lift/getting-started. (Low effort)
Reason
project is not fuzzed
Details
- Warn: no OSSFuzz integration found: Follow the steps in https://github.com/google/oss-fuzz to integrate fuzzing for your project. Over time, try to add fuzzing for more functionalities of your project. (High effort)
- Warn: no OneFuzz integration found: Follow the steps in https://github.com/microsoft/onefuzz to start fuzzing for your project. Over time, try to add fuzzing for more functionalities of your project. (High effort)
- Warn: no GoBuiltInFuzzer integration found: Follow the steps in https://go.dev/doc/fuzz/ to enable fuzzing on your project. Over time, try to add fuzzing for more functionalities of your project. (Medium effort)
- Warn: no PythonAtherisFuzzer integration found: Follow the steps in https://github.com/google/atheris to enable fuzzing on your project. Over time, try to add fuzzing for more functionalities of your project. (Medium effort)
- Warn: no CLibFuzzer integration found: Follow the steps in https://llvm.org/docs/LibFuzzer.html to enable fuzzing on your project. Over time, try to add fuzzing for more functionalities of your project. (Medium effort)
- Warn: no CppLibFuzzer integration found: Follow the steps in https://llvm.org/docs/LibFuzzer.html to enable fuzzing on your project. Over time, try to add fuzzing for more functionalities of your project. (Medium effort)
- Warn: no SwiftLibFuzzer integration found: Follow the steps in https://google.github.io/oss-fuzz/getting-started/new-project-guide/swift-lang/ to enable fuzzing on your project. Over time, try to add fuzzing for more functionalities of your project. (Medium effort)
- Warn: no RustCargoFuzzer integration found: Follow the steps in https://rust-fuzz.github.io/book/cargo-fuzz.html to enable fuzzing on your project. Over time, try to add fuzzing for more functionalities of your project. (Medium effort)
- Warn: no JavaJazzerFuzzer integration found: Follow the steps in https://github.com/CodeIntelligenceTesting/jazzer to enable fuzzing on your project. Over time, try to add fuzzing for more functionalities of your project. (Medium effort)
- Warn: no ClusterFuzzLite integration found: Follow the steps in https://github.com/google/clusterfuzzlite to integrate fuzzing as part of CI. Over time, try to add fuzzing for more functionalities of your project. (High effort)
- Warn: no HaskellPropertyBasedTesting integration found: Use one of the following frameworks to fuzz your project: QuickCheck: https://hackage.haskell.org/package/QuickCheck hedgehog: https://hedgehog.qa/ validity: https://github.com/NorfairKing/validity smallcheck: https://hackage.haskell.org/package/smallcheck hspec: https://hspec.github.io/ tasty: https://hackage.haskell.org/package/tasty (High effort)
- Warn: no TypeScriptPropertyBasedTesting integration found: Use fast-check: https://github.com/dubzzz/fast-check (High effort)
- Warn: no JavaScriptPropertyBasedTesting integration found: Use fast-check: https://github.com/dubzzz/fast-check (High effort)
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 2 are checked with a SAST tool
- Warn: CodeQL tool not detected
Score
5.9
/10
Last Scanned on 2024-11-18T21:23:27Z
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to path-to-regexp
micromatch
Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch.
path-match
wrapper around path-to-regexp for easy route parameters
regexparam
A tiny (399B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` 🙇
nanomatch
Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)