Skip to content

Pattern Matching

When both /lessons/new and /lessons/:slug exist, creating a lesson must not accidentally open a lesson named new. Matching gives static path segments priority over parameters, then falls back to wildcards. Registration order does not choose the winner.

These rules apply to both createRouter in React and createMatcher in the core package. A pathname is the path portion of a URL, such as /lessons/routing; it excludes the origin, query string, and fragment.

Install the package in a TypeScript or JavaScript project:

Terminal window
npm install @studiolambda/router

The package declares Node.js 18 or newer for Node consumers; the Vite quickstart needs the newer toolchain stated there. The core entry point has no React runtime requirement and can also run in the browser. Create a matcher whose generic type describes the values you want to retrieve:

import { createMatcher } from '@studiolambda/router'
const matcher = createMatcher<string>()
matcher.register('/lessons/new', 'create')
matcher.register('/lessons/:slug', 'detail')
matcher.register('/assets/*path', 'asset')
const create = matcher.match('/lessons/new')
const detail = matcher.match('/lessons/routing')
const asset = matcher.match('/assets/images/cover.png')
console.assert(create?.handler === 'create')
console.assert(detail?.params.slug === 'routing')
console.assert(asset?.params.path === 'images/cover.png')
console.assert(matcher.match('/missing') === null)

register mutates the route table and returns nothing. match returns a Resolved<T> object containing handler and params, or null when no complete route matches. A static-only route has an empty parameter record.

Use a defined handler. Values such as 0, false, and '' are valid; undefined means that the node has no registered handler.

PatternMatchesCaptures
/lessons/lessons{}
/lessons/:slug/lessons/routing{ slug: 'routing' }
/assets/*path/assets/a/b.png{ path: 'a/b.png' }
/*/anything/else{ '*': 'anything/else' }

A dynamic segment captures exactly one nonempty segment. A wildcard captures all remaining segments joined by /, and it requires at least one segment. /assets/*path does not match /assets; register /assets separately if you need that page. Likewise, /* does not replace a / route.

Put a wildcard last. Registration does not reject /assets/*path/edit, but matching cannot reach a handler below the wildcard. Optional segments and regular-expression constraints are not part of the pattern syntax. Register separate paths or validate a capture in your application instead.

Empty slash-separated segments are ignored. /lessons/routing, /lessons/routing/, and //lessons//routing therefore match the same route. Static segment comparison is case-sensitive.

At each segment the matcher tries a static branch, then a dynamic branch, then a wildcard. It returns only a complete match. If a more specific branch cannot finish, a less specific branch can still win.

For example, suppose the table contains /lessons/new/edit, /lessons/:slug, and /lessons/*rest. /lessons/new/edit uses the static branch. /lessons/new falls back to the parameter route because the static branch has no handler at that depth. /lessons/new/extra can fall back to the wildcard.

This is not “first registered wins,” and it is not prefix matching. A route for /lessons alone does not match /lessons/routing.

The core matcher splits the string you pass; it does not parse a URL. Given an absolute URL, extract its pathname first:

const url = new URL('https://example.com/lessons/routing?view=notes#summary')
const match = matcher.match(url.pathname)
console.assert(match?.params.slug === 'routing')

The React integration performs this extraction for route matching. Its exported extractPathname(url) helper returns / for nullish or empty input and throws for malformed URLs. Relative input resolves against http://localhost/, not the current browser directory; prefer root-relative hrefs in your route UI.

Captures remain URL-encoded: /lessons/hello%20world produces 'hello%20world'. Decode only where your domain needs decoded text, and handle decodeURIComponent throwing on malformed escapes. Never treat a capture as a trusted filesystem path, SQL value, or authorization decision.

Register each complete pattern once. Duplicate paths throw, including slash-normalized duplicates. Dynamic and wildcard branches also require a consistent capture name at a given position. For example, /lessons/:slug and /lessons/:id/edit conflict; use :slug in both. /assets/*path and /assets/*rest conflict too.

Registration is not transactional: a failed call can leave intermediate nodes behind. Define the table during startup and treat a registration error as a configuration failure rather than continuing with a partly constructed table.

The exported Matcher<T>, Resolved<T>, Options<T>, and Node<T> types describe this contract. createMatcher({ root }) accepts an existing trie root, but retains and mutates it rather than copying it. Omit root for independent tables; sharing it makes registrations visible to every matcher using that root.

For React components, continue with defining routes. useParams() exposes a plain string record, not a generated union of your registered paths: validate parameters where you use them.