Library / SDK
pillarjs/path-to-regexp avatar
pillarjs/path-to-regexp

path-to-regexp: named parameters, reserved characters, and why Express 4 routes now throw

Turn a path string such as `/user/:name` into a regular expression

8,618 stars492 forksTypeScriptMIT

At a glance

What is it?
path-to-regexp compiles Express style route strings into regular expressions and rebuilds paths from parameter objects, with named parameters, segment spanning wildcards and TokenData as an escape hatch. It is aimed strictly at ordered data, and it breaks older Express 4 route syntax on purpose.
Who is it for?
Adopt it when you are writing the routing layer yourself and can commit to the current syntax end to end. Do not expect it to touch query strings, fragments or JSON, and do not lift Express 4 route tables over unchanged, because unnamed wildcards and question mark modifiers now throw instead of matching.
Can I use it commercially?
Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
Is it still maintained?
Yes. The repository last received commits 1 day ago.
What is it written in?
Mainly TypeScript, according to GitHub's language statistics.

Answers come from the project's GitHub data, last synced on November 22, 2026, and from our analysis. They are not legal advice.

From daily snapshots

Star history

  • pillarjs/path-to-regexp8,618 ★ · +10
Star history
Repository2026-09-222026-11-22
pillarjs/path-to-regexp8.6k8.6k

10 Stars in the last 61 days, measured from the daily GitHub snapshot. Compare with other projects

Editorial analysis

An unnamed asterisk now throws instead of matching the rest of the path

An unnamed asterisk no longer matches anything, and that is the most common upgrade break. The wildcard is defined the same way as a regular parameter except for the asterisk prefix, and it must carry a name. Because a wildcard spans multiple segments, its value arrives as an array rather than a string, which is easy to miss when a handler treats every parameter as flat text. Under Express 4 semantics a bare asterisk was legal and swallowed the remainder of the path; in this line of the library it is rejected outright. The consequence for readers is practical: a router table copied from an Express 4 codebase can throw while routes are being registered rather than quietly returning 404s at request time, so route tables need auditing before the version bump, not after.

js
const fn = match("/*splat");

fn("/bar/baz");
//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } }

Question marks, plus signs and parentheses turned into errors

The old modifier characters are error text now, not syntax. Past releases used question mark, asterisk and plus to denote optional or repeating parameters, and regular expression groups were passed through into the generated pattern. This release replaces that surface: braces define optional parts such as /file{.:ext}, a wildcard covers one or more segments as /*path, and using both covers zero or more as /files{/*path}. Parentheses, square brackets and similar characters are reserved so that ambiguous paths throw instead of compiling into something unexpected, and matching one literally requires a backslash escape such as "\\(". The consequence is that no inline constraint can be attached to a parameter. A route that once demanded digits through an embedded character class has no equivalent here, so validation moves to the handler after matching.

js
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 delimiter default is why a named parameter stops at a slash

The boundary between one parameter and the rest of the path comes from a single option. The default delimiter is a slash, which yields a negated class such as [^/] for named parameters, and changing the delimiter moves every parameter boundary with it. Three further defaults shape the generated regexp. Sensitive is false, so patterns stay case insensitive unless you ask otherwise. End is true, meaning a match must reach the end of the input string, and that is the setting responsible for the second common surprise: a route meant to behave as a prefix will refuse to match a longer path. Trailing is true, which allows an optional trailing delimiter. On the matching side, decode defaults to decodeURIComponent and passing false disables all decoding, which matters whenever the same value has to survive a match and a rebuild unchanged.

js
const { regexp, keys } = pathToRegexp("/foo/:bar");

regexp.exec("/foo/123"); //=> ["/foo/123", "123"]

Encoding on by default is what breaks naive round trips

Encoding is on in both directions, and that is exactly what breaks naive round trips. Compile encodes with encodeURIComponent, so an accented value becomes a percent escaped segment, while match decodes with decodeURIComponent on the way back. A router that rebuilds a path and compares it against the raw request path will therefore be comparing two different strings. The guidance for developers is to pass encode false and decode false when rewriting paths with match and compile so raw values stay raw. That shortcut has a cost of its own: with encoding disabled no arrays are accepted, so a wildcard segment cannot be spread across several segments from an array. For characters that are normally percent encoded in paths, such as emoji, parse exposes encodePath, whose default is the identity function and whose recommended implementation is the separate encodeurl package.

js
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"

parse and stringify route around the path syntax

There is a way to use the matching machinery without writing routes in this syntax at all. Parse accepts a path string and returns token data with two properties: tokens, a sequence whose entries are currently of type text, param, wildcard or group, and originalPath, the string that was parsed, retained so error messages can point back at what went wrong. Stringify walks that same structure and produces a path string again. Because match and pathToRegexp accept a token object in place of a string, an application with its own route syntax can build a token array by hand and still reuse matching and compiling. The payoff is that a bracket style route needs no escaping tricks and no reserved character juggling. The cost is that you now own token construction, and a mistake in a token name surfaces as a runtime failure rather than a parse error.

js
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' } }

Only dist ships, under a two kilobyte budget

The published package is build output and nothing else, held to a hard size ceiling. The files list contains only dist/, main and exports both point at dist/index.js, and typings resolve to dist/index.d.ts. A size-limit entry caps dist/index.js at 2 kB, and the test script is defined as running the test suite and then the size check, so a bundle that grows past the ceiling fails the same command that runs the tests. Build and quality tasks all route through one tool: build, lint, format and specs are ts-scripts tasks, bench is vitest bench, and prepare runs install and build so a checkout is compiled before publishing. The manifest declares no runtime dependencies; everything in devDependencies exists for development only, including typescript ^7.0.2, vitest ^5.0.5, recheck ^4.5.0 and @borderless/ts-scripts ^0.15.0. Funding points to an OpenCollective page for express, and History.md sits at the top level next to the manifest.

js
import { match, pathToRegexp, compile, parse, stringify } from "path-to-regexp";

Query strings, fragments and JSON are out of scope

This library will not read a query string, a fragment or a JSON body, and the documentation states that limit directly. The stated scope is ordered data such as paths and hosts, and arbitrarily ordered data is called out as unsupported. The consequence appears the moment someone tries to route on search parameters: the question mark is now a reserved character that produces an error rather than parsing a query. Numeric constraints are missing in the same way. There is no option asking a segment to be four digits, and the delimiter option only decides which characters end a segment, not what they may contain. If routing decisions depend on key value pairs, keep them out of the path string and inspect them in your own layer.

bash
npm install path-to-regexp --save

v8.4.2 shipped in April, master last moved in September

The repository is not archived. The most recent release is v9.0.0 on 2026-10-22, after v8.4.1 on 2026-03-30 and v8.4.2 on 2026-04-01, and the version field in package.json reads 9.0.0. The most recent push to the default branch, master, is dated 2026-09-28. No homepage is declared in the repository metadata, and History.md is the tracked record of older changes. For a reader checking whether the option defaults described here still apply to their dependency, the useful check is the version field rather than a date, because older installs may carry different names and different syntax rules.

Editorial conclusion

Adopt it when you are writing the routing layer yourself and can commit to the current syntax end to end. Do not expect it to touch query strings, fragments or JSON, and do not lift Express 4 route tables over unchanged, because unnamed wildcards and question mark modifiers now throw instead of matching. Verify the version field in package.json against the option defaults you depend on before upgrading.

Frequently asked questions

what is path to regexp

It turns a path string such as /user/:name into a regular expression, and turns parameter objects back into paths. The package exposes match, pathToRegexp, compile, parse and stringify for that one job, under an MIT license.

What is a path pattern in regex?

Here a path pattern is a string where a colon introduces a named parameter, an asterisk introduces a wildcard that spans segments, and braces mark a part of the path as optional. Parameter names can be any valid JavaScript identifier, or double quoted for other characters.

What is a valid URL regex?

The library targets ordered data such as paths and hosts, and can not handle arbitrarily ordered data such as query strings, URL fragments or JSON. There is no URL pattern option to configure, you supply the path segments yourself.

What does regexp stand for?

The pathToRegexp function returns the regexp for matching strings against paths, plus an array of keys for understanding the RegExp#exec matches, so each capture group can be traced back to the parameter that produced it.

What regex pattern can I use to match a 4-digit number?

There is no digit or length constraint built in. The delimiter option sets the boundary for named parameters and defaults to a slash, producing a negated class such as [^/] inside the pattern, so digit checks belong in your handler after matching.

Official sources

  1. Issues
  2. License: MIT
  3. pillarjs/path-to-regexp on GitHub
  4. README
  5. Releases
Add this badge to your README

If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.

Add this badge to your README

markdown
[![Hysen Labs](https://hysenlabs.com/badge/pillarjs-path-to-regexp.svg)](https://hysenlabs.com/projects/pillarjs-path-to-regexp)

Star history chart for your README

markdown
[![Star history](https://hysenlabs.com/chart/pillarjs-path-to-regexp.svg)](https://hysenlabs.com/projects/pillarjs-path-to-regexp)

Was this useful?