Filesystem string manipulation, browser compatibility, slash-normalizing wrappers and URL route patterns are different tasks. The right starting point is the meaning of the string and the runtime that will process it.
Node’s built-in node:path is the normal starting point for filesystem path strings in Node. Installing npm path does not replace that built-in module. The npm copy contains its own older POSIX/Windows implementation, while ordinary core-name resolution still prefers Node’s built-in module.
path-browserify supplies browser-oriented POSIX path functionality. Configure the bundler to resolve the intended shim and any required environment support. It is not an implementation of every current Node method or Windows path rule. A Windows-looking input does not become correctly interpreted merely because the helper accepts a string.
upath wraps path operations to use forward-slash output and adds extension-related helpers. Its current package supplies module entries for contemporary Node and declares Node >=20. Review its documented helper defaults and path results when replacing native path operations; normalization can be the reason to use the package, rather than an incidental formatting change.
upath2 is a separate wrapper around Node path with its own core, platform wrappers and helpers. Its root exports the wrapped path object and registers additional string helpers. It is not automatically an upath alias. Compare actual exports, root/drive behavior, separators and helper return values before migrating.
These operations manipulate strings. Normalizing or resolving a path does not establish that the target exists or read its content.
path-to-regexp parses route templates, builds matchers and compiles values into path strings. Its current syntax includes named parameters and explicit wildcard/optional grouping rules; it is not an arbitrary filesystem path parser or a drop-in regular-expression string from any old routing tutorial. Follow the actual match/compile return contract and encoding options for the route.
Choose route matching for URLs, platform path semantics for filesystem names, and a normalizing wrapper only when that representation is desired. A full-stack application may need more than one of these jobs, but the packages are not interchangeable solutions to one generic “path” problem.
Choose it for route-template parsing, matching and URL path generation. It is not a filesystem normalization or directory traversal library.
Choose an explicit browser-oriented POSIX path shim when the bundler and application need that API. It does not provide the whole current Node path surface or Windows semantics.
Choose slash-normalized path operations and extension helpers when a forward-slash representation is intentional. Its current package requires Node >=20.
Use the npm compatibility copy only when a build explicitly resolves to it. For current Node code, node:path is the built-in implementation without an added npm dependency.
Choose its separate Node path-wrapper API when its normalization and helper semantics fit. Similar naming does not establish identical exports or behavior to upath.
Turn a path string such as
/user/:nameinto a regular expression.
npm install path-to-regexp --save
import { match, pathToRegexp, compile, parse, stringify } from "path-to-regexp";
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").
const fn = match("/:foo/:bar");
fn("/test/route");
//=> { path: '/test/route', params: { foo: 'test', bar: 'route' } }
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).
const fn = match("/*splat");
fn("/bar/baz");
//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } }
Braces can be used to define parts of the path that are optional.
const fn = match("/users{/:id}/delete");
fn("/users/delete");
//=> { path: '/users/delete', params: {} }
fn("/users/123/delete");
//=> { path: '/users/123/delete', params: { id: '123' } }
The match function returns a function for matching strings against a path:
TokenData object, or array of strings and TokenData objects.false to disable all processing. (default: decodeURIComponent)const 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).
The pathToRegexp function returns the regexp for matching strings against paths, and an array of keys for understanding the RegExp#exec matches.
TokenData object, or array of strings and TokenData objects.false)true)[^/] for :named parameters. (default: '/')true)const { regexp, keys } = pathToRegexp("/foo/:bar");
regexp.exec("/foo/123"); //=> ["/foo/123", "123"]
The compile function will return a function for transforming parameters into a valid path:
TokenData object.[^/] for :named parameters. (default: '/')false to disable entirely. (default: encodeURIComponent)const toPath = compile("/user/:id");
toPath({ id: "name" }); //=> "/user/name"
toPath({ id: "café" }); //=> "/user/caf%C3%A9"
const toPathRepeated = compile("/*segment");
toPathRepeated({ segment: ["foo"] }); //=> "/foo"
toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"
// 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"
Transform a TokenData object to a Path-to-RegExp string.
TokenData object.const data = {
tokens: [
{ type: "text", value: "/" },
{ type: "param", name: "foo" },
],
};
const path = stringify(data); //=> "/:foo"
encode: false and decode: false to keep raw paths passed around.encodePath.The parse function accepts a string and returns TokenData, which can be used with match and compile.
x => x, recommended: encodeurl)TokenData has two properties:
text, param, wildcard, or group.parse, shown in error messages to assist debugging.In some applications you may not be able to use the path-to-regexp syntax, but you still want to use this library for match and compile. For example:
import { match } from "path-to-regexp";
const tokens = [
{ type: "text", value: "/" },
{ type: "param", name: "foo" },
];
const originalPath = "/[foo]"; // To help debug error messages.
const path = { tokens, originalPath };
const fn = match(path);
fn("/test"); //=> { path: '/test', params: { foo: 'test' } }
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.
Parameter names must be provided after : or *, for example /*path. They can be valid JavaScript identifiers (e.g. :myName) or JSON strings (:"my-name").
? or +In past releases, ?, *, and + were used to denote optional or repeating parameters. As an alternative, try these:
?), use braces: /file{.:ext}.+), use a wildcard: /*path.*), use both: /files{/*path}.(, ), [, ], 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 match these characters literally, escape them with a backslash, e.g. "\\(".
Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character. For example, :"foo.
Path-To-RegExp breaks compatibility with Express <= 4.x in the following ways:
* must have a name and matches the behavior of parameters :.? is no longer supported, use braces instead: /:file{.:ext}.()[]?+!).:"this".MIT