path-to-regexp

Turn path strings like /user/:id into regular expressions for matching, building, and parsing URLs.

Library
npm
v9.0.0
8,614 stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum. How we score it →
71 /100 Good
Development Activity 72
Maintenance 52
Community 60
Maturity 60
Momentum 40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation. How we score it →
75 /100 Good
Architecture 80
Code Quality 78
Innovation 68
Learning Curve 72

path-to-regexp is the small TypeScript library that converts Express-style path patterns into JavaScript regular expressions, and back again. It exports five focused functions — parse, pathToRegexp, match, compile, and stringify — that together let you tokenize a path pattern, compile it to a RegExp with capture groups, match incoming strings against it, or build a concrete URL from named parameters.

Originally extracted from Express’s internal routing code, it has since become the de facto path-matching engine embedded inside Express, React Router, Vue Router, and dozens of other routing libraries across the npm ecosystem, while remaining usable standalone for anything that needs ordered, delimiter-based pattern matching.

What You Get

  • pathToRegexp() — compiles a path pattern (or array of patterns) into a RegExp plus a keys array describing each capture group
  • match() — a higher-level matcher that returns a function taking a string and returning { path, params } or false
  • compile() — the reverse operation: turns a pattern into a function that builds a concrete path string from a params object
  • parse() / stringify() — tokenize a pattern into a TokenData structure and serialize it back, for programmatic pattern construction
  • Named parameters (:name), wildcards (*name), and optional groups ({...}) with a syntax redesigned in v6+/v8 to eliminate ReDoS-prone constructs

Common Use Cases

  • Implementing the route-matching layer of a custom HTTP server or framework
  • Matching or generating URLs in a client-side single-page-app router
  • Validating and reverse-generating paths from a shared route-definition object (e.g. typed API clients)
  • Building custom middleware that needs to test a request path against a set of patterns without pulling in a full router

Under The Hood

Architecture — The entire library lives in one file, src/index.ts (~670 lines), organized as a small pipeline: parse() walks the pattern character-by-character (via consumeUntil) into a flat Token[] of text/param/wildcard/group nodes wrapped in a TokenData class; pathToRegexp() and compile() both consume that same TokenData rather than re-parsing, so parse/match/build all share one token model. match() is implemented as a thin wrapper around pathToRegexp() that additionally decodes captured params using the token keys array, and compile() walks the tokens in the opposite direction (tokensToFunction) to stitch a params object back into a string, collecting missing parameter names for a TypeError instead of emitting a malformed path.

Tech Stack — Pure TypeScript with zero runtime dependencies, targeting ES module output (dist/index.js, dist/index.d.ts) built via @borderless/ts-scripts. Tests run on Vitest (vitest.config.mts), with @vitest/coverage-v8 for coverage and size-limit enforcing a 2 kB budget on the compiled bundle as part of npm test — a strong signal this library optimizes hard for being embedded inside other packages’ dependency trees.

Code Quality — src/index.spec.ts (24 it() blocks) covers the public API surface directly, while src/cases.spec.ts is a large (~48 KB) table-driven fixture file of pattern/input/expected-match triples run through a shared test harness — the more common pattern for exhaustively covering a parser’s edge cases than dozens of individual it() calls. src/redos.spec.ts specifically fuzzes patterns for catastrophic backtracking using the recheck dev dependency, reflecting the project’s post-v6 rewrite to eliminate ReDoS vulnerabilities that affected earlier majors. Errors are a dedicated PathError class (extends TypeError) that embeds the offending index and a link to a error-reference page, rather than throwing bare strings.

API Design — The five-function surface (parse, pathToRegexp, match, compile, stringify) is small and composable: each function takes and/or returns the same TokenData/pattern types, so you can parse once and feed the result into both match() and compile() without re-parsing. The tradeoff for that safety is a stricter, more explicit syntax than pre-v6 versions — ?, +, and bare regex characters are now reserved and throw PathError with a specific index and link, which front-loads migration pain but removes an entire class of ambiguous-pattern bugs.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers