Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
path-to-regexp
Advanced tools
The path-to-regexp package is a utility for converting paths to and from regular expressions. It is commonly used for routing in web applications, allowing developers to define patterns for URL paths and extract parameters from them.
Path to RegExp Conversion
Convert a path string into a regular expression. It can also extract named parameter keys.
const { pathToRegexp } = require('path-to-regexp');
const keys = [];
const regexp = pathToRegexp('/user/:id', keys);
Extracting Parameters from a Path
Match a path against a pattern and extract the named parameters.
const { match } = require('path-to-regexp');
const matchFn = match('/user/:id');
const result = matchFn('/user/123');
// result.params will contain the extracted parameters
Compile Path to String
Compile a path function from a string pattern, which can then be used to construct paths with parameters.
const { compile } = require('path-to-regexp');
const toPath = compile('/user/:id');
const path = toPath({ id: 123 });
// path will be '/user/123'
Express is a web application framework for Node.js that includes its own routing capabilities, which are similar to path-to-regexp. Express uses path-to-regexp internally for its routing logic.
React Router is a routing library for React that uses path-to-regexp-like pattern matching for defining routes and extracting parameters, but it is specifically tailored for React applications.
url-pattern is another library for matching URLs against patterns and extracting parameters. It offers a similar API to path-to-regexp but with different syntax and additional options for pattern matching.
Turn a path string such as
/user/:name
into a regular expression.
npm install path-to-regexp --save
const { pathToRegexp, match, parse, compile } = require("path-to-regexp");
// pathToRegexp(path, options?)
// match(path, options?)
// parse(path, options?)
// compile(path, options?)
The pathToRegexp
function returns a regular expression with keys
as a property. It accepts the following arguments:
false
)true
)true
)true
)true
)[^/]
for :named
parameters. (default: '/'
)RegExp
. (default: x => x
, recommended: encodeurl
)const regexp = pathToRegexp("/foo/:bar");
// regexp = /^\/+foo(?:\/+([^\/]+?))(?:\/+)?$/i
// keys = [{ name: 'bar', prefix: '', suffix: '', pattern: '', modifier: '' }]
Please note: The RegExp
returned by path-to-regexp
is intended for ordered data (e.g. pathnames, hostnames). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc).
The path argument is used to define parameters and populate keys.
Named parameters are defined by prefixing a colon to the parameter name (:foo
). Parameter names can use any valid unicode identifier characters (similar to JavaScript).
const regexp = pathToRegexp("/:foo/:bar");
// keys = [{ name: 'foo', ... }, { name: 'bar', ... }]
regexp.exec("/test/route");
//=> [ '/test/route', 'test', 'route', index: 0 ]
Parameters can have a custom regexp, which overrides the default match ([^/]+
). For example, you can match digits or names in a path:
const regexpNumbers = pathToRegexp("/icon-:foo(\\d+).png");
// keys = [{ name: 'foo', ... }]
regexpNumbers.exec("/icon-123.png");
//=> ['/icon-123.png', '123']
regexpNumbers.exec("/icon-abc.png");
//=> null
const regexpWord = pathToRegexp("/(user|u)");
// keys = [{ name: 0, ... }]
regexpWord.exec("/u");
//=> ['/u', 'u']
regexpWord.exec("/users");
//=> null
Tip: Backslashes need to be escaped with another backslash in JavaScript strings.
It is possible to define a parameter without a name. The name will be numerically indexed:
const regexp = pathToRegexp("/:foo/(.*)");
// keys = [{ name: 'foo', ... }, { name: '0', ... }]
regexp.exec("/test/route");
//=> [ '/test/route', 'test', 'route', index: 0 ]
Parameters can be wrapped in {}
to create custom prefixes or suffixes for your segment:
const regexp = pathToRegexp("{/:attr1}?{-:attr2}?{-:attr3}?");
regexp.exec("/test");
// => ['/test', 'test', undefined, undefined]
regexp.exec("/test-test");
// => ['/test', 'test', 'test', undefined]
Modifiers are used after parameters with custom prefixes and suffixes ({}
).
Parameters can be suffixed with a question mark (?
) to make the parameter optional.
const regexp = pathToRegexp("/:foo{/:bar}?");
// keys = [{ name: 'foo', ... }, { name: 'bar', prefix: '/', modifier: '?' }]
regexp.exec("/test");
//=> [ '/test', 'test', undefined, index: 0 ]
regexp.exec("/test/route");
//=> [ '/test/route', 'test', 'route', index: 0 ]
Parameters can be suffixed with an asterisk (*
) to denote a zero or more parameter matches.
const regexp = pathToRegexp("{/:foo}*");
// keys = [{ name: 'foo', prefix: '/', modifier: '*' }]
regexp.exec("/foo");
//=> [ '/foo', "foo", index: 0 ]
regexp.exec("/bar/baz");
//=> [ '/bar/baz', 'bar/baz', index: 0 ]
Parameters can be suffixed with a plus sign (+
) to denote a one or more parameter matches.
const regexp = pathToRegexp("{/:foo}+");
// keys = [{ name: 'foo', prefix: '/', modifier: '+' }]
regexp.exec("/");
//=> null
regexp.exec("/bar/baz");
//=> [ '/bar/baz', 'bar/baz', index: 0 ]
A wildcard can also be used. It is roughly equivalent to (.*)
.
const regexp = pathToRegexp("/*");
// keys = [{ name: '0', pattern: '[^\\/]*', separator: '/', modifier: '*' }]
regexp.exec("/");
//=> [ '/', '', index: 0 ]
regexp.exec("/bar/baz");
//=> [ '/bar/baz', 'bar/baz', index: 0 ]
The match
function returns a function for transforming paths into parameters:
pathToRegexp
, plus:
false
to disable entirely. (default: decodeURIComponent
)// Make sure you consistently `decode` segments.
const fn = match("/user/:id", { decode: decodeURIComponent });
fn("/user/123"); //=> { path: '/user/123', index: 0, params: { id: '123' } }
fn("/invalid"); //=> false
fn("/user/caf%C3%A9"); //=> { path: '/user/caf%C3%A9', index: 0, params: { id: 'café' } }
Note: Setting decode: false
disables the "splitting" behavior of repeated parameters, which is useful if you need the exactly matched parameter back.
The compile
function will return a function for transforming parameters into a valid path:
pathToRegexp
(delimiter
, encodePath
, sensitive
, and loose
), plus:
false
the function can produce an invalid (unmatched) path. (default: true
)false
to disable entirely. (default: encodeURIComponent
)const toPath = compile("/user/:id");
toPath({ id: 123 }); //=> "/user/123"
toPath({ id: "café" }); //=> "/user/caf%C3%A9"
toPath({ id: ":/" }); //=> "/user/%3A%2F"
// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted.
const toPathRaw = compile("/user/:id", { encode: false });
toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"
toPathRaw({ id: ":/" }); //=> "/user/:/", throws when `validate: false` is not set.
const toPathRepeated = compile("{/:segment}+");
toPathRepeated({ segment: ["foo"] }); //=> "/foo"
toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"
const toPathRegexp = compile("/user/:id(\\d+)");
toPathRegexp({ id: "123" }); //=> "/user/123"
encode: false
and decode: false
to keep raw paths passed around.encodePath
.loose: false
, trailing: false
, and sensitive: true
.A parse
function is available and returns TokenData
, the set of tokens and other metadata parsed from the input string. TokenData
is can passed directly into pathToRegexp
, match
, and compile
. It accepts only two options, delimiter
and encodePath
, which makes those options redundant in the above methods.
name
The name of the tokenprefix
(optional) The prefix string for the segment (e.g. "/"
)suffix
(optional) The suffix string for the segment (e.g. ""
)pattern
(optional) The pattern defined to match this tokenmodifier
(optional) The modifier character used for the segment (e.g. ?
)separator
(optional) The string used to separate repeated parametersAn 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.
?
, *
, or +
In previous major versions /
and .
were used as implicit prefixes of parameters. So /:key?
was implicitly {/:key}?
. For example:
/:key?
→ {/:key}?
or /:key*
→ {/:key}*
or /:key+
→ {/:key}+
.:key?
→ {.:key}?
or .:key*
→ {.:key}*
or .:key+
→ {.:key}+
:key?
→ {:key}?
or :key*
→ {:key}*
or :key+
→ {:key}+
!
, @
, ,
, or ;
These characters have been reserved for future use.
Path-To-RegExp breaks compatibility with Express <= 4.x
in the following ways:
()
.
/[a-z]+
to match /test
.?
optional character must be used after {}
.{}?*+@!;
).[a-z0-9]
.MIT
FAQs
Express style path to RegExp utility
The npm package path-to-regexp receives a total of 46,650,749 weekly downloads. As such, path-to-regexp popularity was classified as popular.
We found that path-to-regexp demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.