Path-to-RegExp: Convert URL Path Patterns to Regular Expressions
Turn a path string such as `/user/:name` into a regular expression
At a glance
- What is it?
- A tiny JavaScript/TypeScript library that converts Express-style path patterns (such as `/user/:name`) into regular expressions for route matching and URL construction. Widely used in Node.js routers and web frameworks.
- Who is it for?
- Path-to-RegExp is essential for web frameworks, routers, and developers who need to parse and match URL paths against patterns. Adopt it if you are building a router, URL matcher, or any system that needs to extract parameters from paths and reconstruct them.
- 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 5 days 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 October 3, 2026, and from our analysis. They are not legal advice.
Editorial analysis
Converting Express-Style Paths to Regular Expressions
Path-to-RegExp solves the problem of converting human-readable path patterns into regular expressions for matching and generating URLs. It converts a path string such as `/user/:name` into a regular expression. This is the core logic used in Express.js routing and many other web frameworks. Instead of manually writing regex patterns to match routes, you write readable path syntax, and the library handles the conversion and matching. The library exports five functions: `match`, `pathToRegexp`, `compile`, `parse`, and `stringify`. Each function serves a different part of the routing pipeline. The library is small (2 kB enforced in package.json), focused, and handles ordered data like paths and hostnames. The README explicitly states it cannot handle arbitrarily ordered data such as query strings, URL fragments, JSON objects, or unordered parameters.
Installation and basic usage
Install Path-to-RegExp from npm:
npm install path-to-regexp --saveOnce installed, import the functions you need:
const {
match,
pathToRegexp,
compile,
parse,
stringify,
} = require('path-to-regexp');The package exports five main functions. You can also import from TypeScript modules, as the package includes type definitions in `dist/index.d.ts`. The package.json specifies version 8.4.2 as the latest release.
Five functions for path matching and generation
Path-to-RegExp exports five main functions. The `match` function creates a matcher function that extracts parameters from a path string. Given a path pattern, `match` returns a function that takes a path and returns an object with the matched path and extracted parameters. The `pathToRegexp` function is lower-level: it returns a RegExp object and an array of keys for understanding `RegExp#exec` matches. The `compile` function does the reverse of matching: given parameters, it generates a valid path string. The `parse` function converts a path string to a TokenData object (tokens and the original path). The `stringify` function converts TokenData back to a path string. Each function is designed for a specific part of the routing pipeline, allowing you to compose them based on your needs.
Pattern Syntax: Parameters, Wildcards, and Optional Segments
Path-to-RegExp uses intuitive syntax for routes. Named parameters are prefixed with a colon: `:foo` matches a single segment up to the next delimiter. The README example `/:foo/:bar` matches paths like `/test/route` and extracts `{ foo: 'test', bar: 'route' }`. Parameter names can be any valid JavaScript identifier, or be double-quoted to use other characters: `:"param-name"` allows hyphens and other special characters in parameter names. Wildcards use an asterisk: `*splat` matches one or more segments across multiple path levels. For example, `/*splat` on `/bar/baz` extracts `{ splat: ['bar', 'baz'] }` as an array. Optional parts use braces: `/users{/:id}/delete` matches both `/users/delete` (without the id) and `/users/123/delete` (with the id). The `pathToRegexp` function accepts options to control matching behavior: `sensitive` (default false) enables case-sensitive matching, `end` (default true) requires the entire string to match, `delimiter` (default '/') sets the segment delimiter, and `trailing` (default true) allows optional trailing delimiters. When matching parameters match up to the end of the segment or up to any proceeding tokens, you can control this behavior with the options you pass to `pathToRegexp`.
Compiling Paths from Parameters
The `compile` function does the reverse of matching: given a path pattern and parameters, generate a valid path string. For example, `compile("/user/:id")` returns a function that transforms `{ id: 'name' }` into `/user/name`. Wildcard parameters become arrays: `compile("/*segment")` with `{ segment: ['a', 'b', 'c'] }` produces `/a/b/c`. Multiple repetitions are also possible: `compile("/*segment")({ segment: ['foo'] })` returns `/foo`. By default, parameters are URL-encoded using `encodeURIComponent`: `{ id: 'café' }` becomes `/user/caf%C3%A9`. You can disable encoding by passing `{ encode: false }` in the options if you manage encoding yourself. The `compile` function also accepts a `delimiter` option to use a different separator. The README recommends using `encode: false` and `decode: false` when rewriting paths with both `match` and `compile` to avoid double-encoding. The README demonstrates this pattern when you are rewriting paths and want to keep them raw throughout the pipeline.
Parsing tokens and custom path representations
The `parse` function converts a path string to a TokenData object with two properties: `tokens` (a sequence of text, param, wildcard, or group elements) and `originalPath` (used for debugging error messages). The `stringify` function reverses this, converting TokenData back to a path string. This two-step process allows you to programmatically construct or analyze routing patterns. The token types include text (literal characters), param (named parameters), wildcard (glob patterns), and group (optional segments). You can also provide custom TokenData directly to `match` and `compile`. This is useful if your application uses a different path syntax but still wants to leverage the library's matching and compilation logic. For example, if your syntax uses brackets instead of colons (e.g., `/[foo]`), you can parse it into TokenData and reuse it. The README includes an example of custom token construction where you manually build the tokens array and originalPath, then pass it to `match`. This gives you complete control over the routing syntax while reusing the library's matching engine.
Handling encoded paths and special characters
The `parse` function accepts an `encodePath` option for encoding input strings. By default it does nothing (`x => x`), but the README recommends using the `encodeurl` library for paths with emoji and other unusual encoded characters that need special handling. When you compile a path with encoded parameters, they are decoded back using `decodeURIComponent` by default in the `match` function. The `match` function accepts a `decode` option: set it to false to disable decoding and receive raw parameter values. This is useful if you are already managing encoding elsewhere in your pipeline to avoid double-encoding. Similarly, the `compile` function has an `encode` option that defaults to `encodeURIComponent`. The package limits the output to 2 kB as specified in package.json size-limit configuration, enforcing small bundle size at build time with the size-limit tool. The build process runs size checks automatically during testing.
Version 8 breaking changes from Express.js 4.x
Path-to-RegExp version 8 introduces breaking changes from Express <= 4.x. Wildcards must now have a name: `/*path` is valid, `/*` alone is not. The optional character `?` is no longer supported; use braces instead: `/file{.:ext}` for optional extension. Regexp characters like `(`, `)`, `[`, `]` are no longer supported; they are reserved to avoid ambiguity and ensure the path syntax is clear. To match these characters literally, escape them with a backslash: `"\\("`. The README documents error messages to help with migration: "Missing parameter name" appears when you forget to name a parameter, "Unexpected `?` or `+`" appears when using old optional syntax, and "Unexpected `(`, `)`, `[`, `]`" appears when using reserved characters. The documentation also covers unterminated quote errors and migration advice. Recent releases include 8.4.2, 8.4.1, and 8.4.0. The last push was on 2026-09-22, indicating active maintenance. The package includes TypeScript type definitions in `dist/index.d.ts`. The repository uses GitHub for coordination and issues.
When Path-to-RegExp is insufficient
Path-to-RegExp is designed for ordered, hierarchical data like URLs and hostnames. The README explicitly states it cannot handle arbitrarily ordered data such as query strings, URL fragments, JSON objects, or unordered parameters. The distinction is important: path matching requires understanding hierarchy (parent before child, left before right), while query strings and fragments are unordered key-value pairs. If your routing needs are very complex, with many conditional branches, conditional logic, or deeply nested patterns, you may need a more specialized router that understands your full application context. The library also does not handle percent-decoding of non-ASCII characters by default; the README recommends using the `encodeurl` library for paths with emoji or other unusual characters. The small 2 kB bundle size means the library is focused and minimal; it does not include routing context management, middleware support, or request/response handling. It is a utility library, not a framework.
Editorial conclusion
Path-to-RegExp is essential for web frameworks, routers, and developers who need to parse and match URL paths against patterns. Adopt it if you are building a router, URL matcher, or any system that needs to extract parameters from paths and reconstruct them. The library is small, battle-tested, widely used in production Node.js codebases, and well-maintained. Before adopting, verify that the pattern syntax matches your routing needs: parameter syntax (`:foo`), wildcards (`*foo`), optional segments (`{/:id}`), and case sensitivity options must align with your application's requirements.
Frequently asked questions
What is path-to-regexp?
Path-to-RegExp is a JavaScript library that converts Express-style path patterns (like `/user/:name`) into regular expressions for route matching and URL construction. It is tiny (2 KB) and widely used in Node.js web frameworks.
How do I match a path with path-to-regexp?
Use the `match` function: `const fn = match('/:foo/:bar'); fn('/test/route')` returns `{ path: '/test/route', params: { foo: 'test', bar: 'route' } }`.
Can I make part of a path optional?
Yes, use braces. For example, `/users{/:id}/delete` matches both `/users/delete` and `/users/123/delete`. The README shows this syntax for optional segments.
What is a wildcard in path-to-regexp?
A wildcard parameter uses an asterisk: `*splat`. It matches one or more segments across multiple path levels. For example, `/*splat` matching `/bar/baz` returns `{ splat: ['bar', 'baz'] }`.
How does the compile function work?
The `compile` function reverses matching: given parameters, it generates a path. For example, `compile('/user/:id')({ id: 'john' })` returns `/user/john`. Parameters are URL-encoded by default.
What changed from version 4.x to version 8?
Version 8 breaks compatibility: wildcards must have names, optional `?` syntax is removed in favor of braces, and regexp characters are no longer supported. Escape special characters with backslash.
Official sources
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.
[](https://hysenlabs.com/projects/pillarjs-path-to-regexp)